Codeforces-873B:Balanced Substring(DP)

来源:互联网 发布:淘宝买家怎么买运费险 编辑:程序博客网 时间:2024/04/23 19:24

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
811010111
output
4
input
3111
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.


思路:num[i][2]分别记录[0,i]中0的个数和1的个数。那么在第i个字符处,若存在k<i使得num[k][0]-num[k][1]==num[i][0]-num[i][1],那么[k+1,i]这一段为balanced substring。

#include<bits/stdc++.h>using namespace std;const int MAX=2e5;int n,num[MAX][2],ans=0;int one[MAX],zero[MAX];char s[MAX];int main(){    memset(num,0,sizeof num);    memset(one,1e9+7,sizeof one);    memset(zero,1e9+7,sizeof zero);    scanf("%d%s",&n,s+1);    for(int i=1;i<=n;i++)    {        num[i][1]=num[i-1][1];        num[i][0]=num[i-1][0];        num[i][s[i]-'0']++;        if(num[i][0]>num[i][1])zero[num[i][0]-num[i][1]]=min(zero[num[i][0]-num[i][1]],i);        if(num[i][1]>num[i][0])one[num[i][1]-num[i][0]]=min(one[num[i][1]-num[i][0]],i);    }    for(int i=1;i<=n;i++)    {        if(num[i][0]==num[i][1])ans=max(ans,i);        else        {            if(num[i][0]>num[i][1])ans=max(ans,i-zero[num[i][0]-num[i][1]]);            if(num[i][1]>num[i][0])ans=max(ans,i-one[num[i][1]-num[i][0]]);        }    }    cout<<ans<<endl;    return 0;}



原创粉丝点击