B. Balanced Substring
Time limit per test1 second
Memory limit per test256 megabytes
Inputstandard input
Outputstandard output
You are 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 are have to determine the length of the longest balanced substring of s.
Input
The 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 "the" 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.
How many substrings in the string have the same number of 0 and 1
Idea: replace 0 with 1, find the prefix and, record the prefix and the position, and update the maximum length when the same prefix is encountered.
AC Code:
#include <bits/stdc++.h> using namespace std; const int MAX = 1e5 + int N,a[max]; Map &L
T;int,int> m;
Char S[max];
int main () {int n;
scanf ("%d%s", &n,s + 1);
for (int i = 1; I <= n; i++) if (s[i] = = ' 0 ') a[i] =-1;
else a[i] = 1;
int ans = 0,sum = 0;
M[0] = 1;
for (int i = 1; I <= n; i++) {ans = a[i];
if (M[ans]) sum = max (Sum,i-m[ans] + 1);
else M[ans] = i + 1;
printf ("%d\n", sum);
return 0; }