CodeForces - 873B Balanced Substring

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的个数相等的话 就说这个子串平衡
求 最长平衡子串的长度

这个问题可以转化成,最长子序列问题。

不知道怎么处理,后来听说 把0转化成-1,这样就可以求子序列为0时的最长长度。

有才的网友,借用map,因为map不能重复插入,第一次插入的一定是第一次出现的,巧妙。

 这个挺关键的:如果之前存在过这个和,现在又出现了,说明这个区间1,0个数是相同的,相减为长度

 我自己也手动模拟了一下,(相信你也看不懂= =,,,,属于自己能看懂序列。。。hh)

#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
#include <string>
#include <map>
#include <set>
#include <vector>
#define maxn 100005
using namespace std;
//最长子序列问题  求最长子序列为0时最长序列
int main()
{
    int n,maxx=0,sum=0;
    string s;
    int a[maxn];
    map<int,int> ma;
    ma.clear();
    cin>>n>>s;

    for(int i=0;i<n;i++)
    {
        if(s[i]=='0')
        {
            a[i+1]=-1;
        }else if(s[i]=='1'){
            a[i+1]=1;
        }
    }
    for(int i=1;i<=n;i++)//i要从1开始。所以 都数组下标都加了一
    {
        sum+=a[i];
        if(ma[sum])
        {
            maxx=max(maxx,i-ma[sum]);////如果之前存在过这个和,现在又出现了,说明这个区间1,0个数是相同的,相减为长度
        }else ma[sum]=i;//利用map不能重复插入的特性,所以如果存在一定是这个值第一次出现时的位置,所以这样后面再出现就相减求区间长度On复杂度求出
        if(sum==0)
            maxx=max(maxx,i);////如果前缀和出现零一定说明从一开始就是1,0个数相同,否则前缀和一定不可能为零
    }
    //for(int i=0;i<n;i++)
    //cout<<a[i]<<" ";
    //cout<<zero<<" "<<one<<endl;
    cout<<maxx<<endl;
    return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_40046426/article/details/81431606