[Codeforces 873B]Balanced Substring

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]$是一段可行区间。

 1 //It is made by Awson on 2017.10.15
 2 #include <set>
 3 #include <map>
 4 #include <cmath>
 5 #include <ctime>
 6 #include <cmath>
 7 #include <stack>
 8 #include <queue>
 9 #include <vector>
10 #include <string>
11 #include <cstdio>
12 #include <cstdlib>
13 #include <cstring>
14 #include <iostream>
15 #include <algorithm>
16 #define LL long long
17 #define Min(a, b) ((a) < (b) ? (a) : (b))
18 #define Max(a, b) ((a) > (b) ? (a) : (b))
19 #define sqr(x) ((x)*(x))
20 using namespace std;
21 const int N = 100000;
22 const int INF = ~0u>>1;
23 void read(int &x) {
24     char ch; bool flag = 0;
25     for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar());
26     for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar());
27     x *= 1-2*flag;
28 }
29 
30 int n, a, zero[N+5], one[N+5];
31 int sum, ans;
32 char ch[N+5];
33 
34 void work() {
35     read(n); scanf("%s", ch+1);
36     for (int i = 1; i <= n; i++) {
37         a = ch[i]-48;
38         if (a == 1) sum++;
39         else sum--;
40         if (sum > 0) {
41             if (one[sum]) ans = Max(ans, i-one[sum]);
42             else one[sum] = i;
43         }else if (sum < 0) {
44             if (zero[sum]) ans = Max(ans, i-zero[sum]);
45             else zero[sum] = i;
46         }
47         else ans = i;
48     }
49     printf("%d\n", ans);
50 }
51 int main() {
52     work();
53     return 0;
54 }

 

转载于:https://www.cnblogs.com/NaVi-Awson/p/7673779.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值