CF873B Balanced Substring (前缀和)
蛮有意思的一道题,不过还是.....................因为CF评测坏了,没有试过是否可过.
显然求(sum[i][0] - sum[l][0] = sum[i][1] - sum[l][1])
(sum[i][0] - sum[l][1] = sum[i][0] - sum[l][0])
然后hash一下DP即可.
#include <iostream>
#include <cstdio>
using namespace std;
#define rep(i,x,p) for(int i = x;i <= p;++ i)
const int maxN = 100000 + 7;
/*
设状态sum[i]
sum[i][0]表示前i位0数的个数
sum[i][1]表示前i位1数的个数
*/
int f[maxN][2]; // f[i][0]表示 sum[i][0] - sum[i][1]最远位置.
// f[i][1]表示 sum[i][1] - sum[i][0]最远位置.
int a[maxN];
char c[maxN];
int sum[maxN][2];
inline int max(int a,int b) {return a > b ? a : b;}
inline int min(int a,int b) {return a > b ? b : a;}
inline int read() {
int x = 0,f = 1;char c = getchar();
while(c < '0' || c > '9') {if(c == '-')f = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x * 10 + c - '0';c = getchar();}
return x * f;
}
int main() {
int n = 0,ans = 0;
n = read();
rep(i,1,n) scanf("%1d",&a[i]);
rep(i,1,n) {
sum[i][0] = sum[i - 1][0];
sum[i][1] = sum[i - 1][1];
a[i] == 0 ? sum[i][0] ++ : sum[i][1] ++;
if(sum[i][0] > sum[i][1]) {
int tmp = sum[i][0] - sum[i][1];
if(f[tmp][0]) ans = max(ans,i - f[tmp][0]);
else f[tmp][0] = i;
}
else {
int tmp = sum[i][1] - sum[i][0];
if(f[tmp][1]) ans = max(ans,i - f[tmp][1]);
else f[tmp][1] = i;
}
}
printf("%d
", ans);
return 0;
}