Educational Codeforces Round 30 - B. Balanced Substring

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
8
11010111
output
4
input
3
111
output
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.


题意:

求最长子串的长度,这个子串中0,1的数量相等。

POINT:

记录0,1,遇1值+1,遇0值-1。记录每一个出现的数的第一次的位置,当他再次出现,则第一次和再次出现的位置中就是0,1次数相等的子串。判断长度。

特殊的,值为0时,就直接把当前位置和ans比较,因为这是便利到的位置和之前的所有0,1都抵消了。

      0  1  0 1   0   0   0   1  1   1  1 1  

  0 -1  0 -1 0 -1  -2  -3  -2 -1   0  1 2

如上图。

这题要反思,临睡前才想出来。

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn =100044;
char s[maxn];
int a[maxn];
mapfir;
maplast;
int main()
{
    int n;
    cin>>n;
    scanf("%s",s+1);
    a[0]=0;
    int ans=0;
    for(int i=1;i<=n;i++){
        if(s[i]=='0') a[i]=a[i-1]-1;
        else a[i]=a[i-1]+1;
        if(fir[a[i]]==0){
            fir[a[i]]=i;
        }
        last[a[i]]=i;
        if(a[i]!=0)
            ans=max(last[a[i]]-fir[a[i]],ans);
        else
            ans=max(last[a[i]],ans);
    }
    printf("%d\n",ans);
    return 0;
}



你可能感兴趣的:(CodeForces,杂)