B. Balanced Substring
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length of the longest balanced substring of s.
Input
The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s.
The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.
Output
If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.
Examples
input
Copy
8 11010111
output
Copy
4
input
Copy
3 111
output
Copy
0
Note
In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.
In the second example it's impossible to find a non-empty balanced substring.
思路: 1为+1,0为-1,寻找值一样的最长间隔
#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string.h>
using namespace std;
int main(){
int n;
string s;
cin>>n>>s;
int sum=0;
int idx[100005],iidx[100005];
const int inf=0x3f3f3f3f;
memset(idx,inf,sizeof(idx));
memset(iidx,inf,sizeof(iidx));
int ans=0;
for(int i=0,j=1;i<n;i++,j++){
if(s[i]=='0') sum--;
else sum++;
if(sum>0&&idx[sum]==inf) idx[sum]=j;
else if(sum<0&&iidx[-sum]==inf) iidx[-sum]=j;
if(sum>0)
ans=max(ans,j-idx[sum]);
else if(sum==0) ans=max(ans,j);
else ans=max(ans,j-iidx[-sum]);
//cout<<i<<" "<<sum<<endl;
}
cout<<ans<<endl;
return 0;
}
/*
11010111 0
012121234 3
0123456789 10
0 0 1 1 1 1 0 0
-1-2-1 0 1 2 1 0
1 2 3 4 5 6 7 8 9
8
00111100
*/