Crazy Binary String
解题思路
把1记为1,把0记为-1,然后求前缀和,前缀和相等的就说明中间的01数一样。只要记录前缀和数值出现的位置即可更新出答案。
代码如下
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int N = 100005;
int l[N << 1];
int sum[N];
int main()
{
int n;
scanf("%d%*c", &n);
int ans1 = 0;
int a, b;
a = b = 0;
for(int i = 1; i <= n; i ++){
char ch = getchar();
if(ch == '0'){
++a;
sum[i] = sum[i - 1] - 1;
}
else if(ch == '1'){
++b;
sum[i] = sum[i - 1] + 1;
}
if(l[sum[i] + N] || sum[i] == 0)
ans1 = max(ans1, i - l[sum[i] + N]);
else
l[sum[i] + N] = i;
}
cout << ans1 << " " << 2 * min(a, b) << endl;
return 0;
}