题解:CF2267E Clean Substrings

· · 题解

显然记一个子串的段数是 x,答案就是 \displaystyle\lfloor\frac{x}{2}\rfloor。

而 \displaystyle\lfloor\frac{x}{2}\rfloor=\frac{x-(x\bmod 2)}{2}。

$\sum(x\bmod 2)$ 也是很好算的,注意到段数为奇数当且仅当区间首尾相同,所以随便挑两个相同的字符都是一个贡献。 复杂度 $O(n+q)$。 ::::success[Code] ```cpp #include<bits/stdc++.h> using namespace std; #define int long long #define MAXN 300005 int n,q,a[MAXN],Q[MAXN]; char s[MAXN]; inline int calc( int c0 , int c1 ){ return c0 * ( c0 - 1 ) / 2 + c1 * ( c1 - 1 ) / 2; } inline void solve(){ scanf("%lld%lld%s",&n,&q,s + 1); int c0 = 0,c1 = 0; for( int i = 1 ; i <= n ; i ++ ) a[i] = s[i] - '0',c0 += !a[i],c1 += a[i]; int ans = 0; for( int i = 1 ; i < n ; i ++ ) if( s[i] != s[i + 1] ) ans += i * ( n - i ); printf("%lld ",( ( ans - calc( c0 , c1 ) ) + n * ( n - 1 ) / 2 ) / 2); for( int i = 1 ; i <= q ; i ++ ){ int x; scanf("%lld",&x); if( x > 1 && a[x - 1] != a[x] ) ans -= ( x - 1 ) * ( n - x + 1 ); if( x < n && a[x] != a[x + 1] ) ans -= x * ( n - x ); if( a[x] == 0 ) c0 --; else c1 --; a[x] ^= 1; if( a[x] == 0 ) c0 ++; else c1 ++; if( x > 1 && a[x - 1] != a[x] ) ans += ( x - 1 ) * ( n - x + 1 ); if( x < n && a[x] != a[x + 1] ) ans += x * ( n - x ); printf("%lld ",( ( ans - calc( c0 , c1 ) ) + n * ( n - 1 ) / 2 ) / 2); } puts(""); } signed main(){ int t; scanf("%lld",&t); while( t -- ) solve(); return 0; } ``` ::::