CF873B Balanced Substring (前綴和)
阿新 • • 發佈:2018-10-16
iostream ace clu substring read fine tchar ring name
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\n", ans); return 0; }
CF873B Balanced Substring (前綴和)