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 }