AT_agc069_c [AGC069C] AB*A Changing

· · 题解

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

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

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

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

时间复杂度 O(n)。

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");
}