[Codeforces 873B]Balanced Substring

2023-05-20,,

Description

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.

Sample Input

8
11010111

Sample Output

4

Hint

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.

题解

令所有$0$为$-1$,做一遍前缀和,若$L$,$R$前缀和相同,则$[L+1,R]$是一段可行区间。

 //It is made by Awson on 2017.10.15
#include <set>
#include <map>
#include <cmath>
#include <ctime>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define sqr(x) ((x)*(x))
using namespace std;
const int N = ;
const int INF = ~0u>>;
void read(int &x) {
char ch; bool flag = ;
for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || ); ch = getchar());
for (x = ; isdigit(ch); x = (x<<)+(x<<)+ch-, ch = getchar());
x *= -*flag;
} int n, a, zero[N+], one[N+];
int sum, ans;
char ch[N+]; void work() {
read(n); scanf("%s", ch+);
for (int i = ; i <= n; i++) {
a = ch[i]-;
if (a == ) sum++;
else sum--;
if (sum > ) {
if (one[sum]) ans = Max(ans, i-one[sum]);
else one[sum] = i;
}else if (sum < ) {
if (zero[sum]) ans = Max(ans, i-zero[sum]);
else zero[sum] = i;
}
else ans = i;
}
printf("%d\n", ans);
}
int main() {
work();
return ;
}

[Codeforces 873B]Balanced Substring的相关教程结束。

《[Codeforces 873B]Balanced Substring.doc》

下载本文的Word格式文档,以方便收藏与打印。