B. Balanced Substring
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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.
题意:
给你一个长度为n的0,1串,问在他的子串中,满足0和1的数目相同的子串的最大长度为多少?
分析:
一个子串中0,1的数目相同 => 0,1的数目各占一半
若我们将0看成-1,那么问题就转化为了:求一段和为0的子串的最大长度了
最好想到的就是枚举左右端点,进行判断。但是时间复杂度为O(n^2) 超时
那么我么就要进行思维上的优化了!!!
由于一个子串的和,可以用端点处的前缀sum和之差来表示,所以我们想到了前缀和
若子串s[L….R]的和为0,那么一定有sum[R] == sum[L-1]
我们只需要找到所有的前缀和出现的最左边的位置和最后的位置,他们的差值的最大值就是答案了
具体步骤:
我们用map来记录每种前缀和出现的第一个位置。
当我们从左向右计算前缀和时,假设当前前缀和为x,若x没有出现过,那么当前位置一定是x的最左边的位置,若x已经出现过,即map[x]的值为x出现的最左边的位置,那么两个位置之差的长度就是一段和为0的子串的长度。
注意:由于map[x]的初始化值为0,并且我们是用map[x]是否为0来判断x是否出现过。所有不存在map[0] = 0的情况。所以前缀和为0的情况要单独处理。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
const int maxn = 100010;
int sum,ans,n;
char s[maxn];
int main()
{
while(scanf("%d",&n)!=EOF)
{
scanf("%s",s+1);
sum = 0; ans = 0;
map<int,int> mmap;
for(int i=1;i<=n;i++)
{
if(s[i] == '1') sum++;
else sum--;
if(sum == 0) ans = max(ans,i);
if(mmap[sum])
{
ans = max(ans,i-mmap[sum]);
}
else mmap[sum] = i;
}
printf("%d\n",ans);
}
return 0;
}