跳到正文

题解

题解:CF2267E Clean Substrings

MaxBlazeResFire约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年9月29日
收录
2026年11月6日
更新
2026年11月21日
篇幅
约 3 分钟
获赞
5
题目
CF2267E

版本

  1. v1当前

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

而 ⌊x2⌋=x−(x mod 2)2\displaystyle\lfloor\frac{x}{2}\rfloor=\frac{x-(x\bmod 2)}{2}。

∑x\sum x 是很好算的,因为段数等于相异分界数 +1+1,而每个分界点 (i,i+1)(i,i+1) 给 i(n−i)i(n-i) 个区间贡献,直接计算。

∑(x mod 2)\sum(x\bmod 2) 也是很好算的,注意到段数为奇数当且仅当区间首尾相同,所以随便挑两个相同的字符都是一个贡献。

复杂度 O(n+q)O(n+q)。

Code
C++
#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;
}
原文