Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /***************************************************************************
- * ####### # *
- * # # # ###### # # # # #### # # # # # *
- * # # # # # # ## # # # # # # # *
- * # ###### ##### # # # # # #### ###### # # # *
- * # # # # ####### # # # # # # # # # *
- * # # # # # # # ## # # # # # # # *
- * # # # ###### # # # # #### # # #### ###### *
- ***************************************************************************/
- #include<bits/stdc++.h>
- #define ll long long
- #define pb push_back
- #define endl '\n'
- #define pii pair<ll int,ll int>
- #define vi vector<ll int>
- #define all(a) (a).begin(),(a).end()
- #define F first
- #define S second
- #define sz(x) (ll int)x.size()
- #define hell 1000000007
- #define rep(i,a,b) for(ll int i=a;i<b;i++)
- #define lbnd lower_bound
- #define ubnd upper_bound
- #define bs binary_search
- #define mp make_pair
- using namespace std;
- #define N 100005
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(0);
- cout.tie(0);
- int TESTS=1;
- cin>>TESTS;
- while(TESTS--)
- {
- ll n;
- string s;
- cin>>n;
- cin>>s;
- vi dp(n+1);
- ll sum=0,mx=0,mn=0;
- dp[0]=0;
- rep(i,0,n)
- {
- if(s[i]=='0')
- sum--;
- else
- sum++;
- dp[i+1]=sum;
- if(sum>mx)
- mx=sum;
- if(sum<mn)
- mn=sum;
- }
- if(mn>=0)
- {
- cout<<n<<endl;
- continue;
- }
- vi vdp(mx-mn+1,-2);
- for(ll i=n;i>=0;i--)
- {
- if(vdp[dp[i]-mn]==-2)
- vdp[dp[i]-mn]=i;
- }
- ll fd=-1;
- for(ll i=mx-mn;i>=0;i--)
- {
- if(vdp[i]>fd)
- fd=vdp[i];
- vdp[i]=fd;
- }
- // rep(i,0,mx-mn+1)
- // cout<<vdp[i]<<" ";
- // cout<<endl;
- ll val=0,i=0,ref,ans=0;
- for(i=0;i<=n;i++)
- {
- val=dp[i];
- // if(val==mx)
- // {
- // continue;
- // }
- ref=vdp[val+1-mn];
- if(ref>i)
- {
- ans+=ref-i;
- i=ref;
- }
- }
- cout<<ans<<endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement