跳到正文

题解

AT_agc069_c [AGC069C] AB*A Changing

Rainbow_qwq约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年4月7日
更新
2026年4月7日
篇幅
约 2 分钟

版本

  1. v1当前

从左到右扫描序列,把每次操作的线段看作左边加入/右边删除,记录经过当前位置的线段数量。

在每个位置会有若干条线段开始(操作 A→BA\to B),若干条线段结束(操作 A→BA\to B),有若干条线段经过(操作 B→AB\to A)。

考虑 DP,设 f(i,j)f(i,j) 表示扫到第 ii 个位置,往后还有 jj 条线段没结束。转移时枚举一下删除/加入的线段数量,并且要满足 sis_i 变化的要求(如 A→B→A→⋯→BA\to B\to A\to \cdots\to B)。

然后由于一些不知道什么原因,DP 的第二维只需要开一个很小的常数就对了(credit from noshi91,proof by AC,我不会证),实际上只需要开到 44。

时间复杂度 O(n)O(n)。

C++
int n;
char s[maxn],t[maxn];
int f[maxn][13];
void work()
{
	n=read(),scanf("%s%s",s+1,t+1);
	memset(f[0],63,sizeof f[0]);
	f[0][0]=0;
	int B=4;
	For(i,1,n){
		memset(f[i],63,sizeof f[i]);
		int now=(s[i]=='B');
		int nd=(t[i]=='B');
		int c01=0,c10=0;
		For(j,0,B){
			if(now==nd){
				For(k,0,B){
					int x=k-c10;
					if(x>=0 && x<=c01){
						int t=(k-x)+(c01-x);
						if(t>=0 && t<=B)
							f[i][t]=min(f[i][t],f[i-1][k]+(c01-x));
					}
				}
			}
			if(now==0)++c01;
			else ++c10;
			now^=1;
		}
	}
	if(f[n][0]<inf)cout<<f[n][0]<<"\n";
	else puts("-1");
}
原文