题解:P12932 [NOISG 2020 Prelim] Visiting Singapore

· · 题解

蓝到绿。

分析

题意是说如果选 C 的子序列,如果选了 len 个点,这些选出来的点将 C 分成了 x 段,则代价是 xA+(|C|-len)B。现在要选择 S 的一个子序列和 T 的一个子序列,使得它们的代价和加上选出来的点的价值和尽可能大。求最大值。同时,可以删掉 S 的一段前缀和一段后缀,这段前缀不计算在 S 的代价中。

注意到 n,m \le 5000,考虑暴力 DP。定义状态函数 f_{i,j,0/1,0/1,0/1} 表示在 S 的前 i 位匹配了 T 的前 j 位,且 S_{i} 是否跳过,T_j 是否跳过,是否参加了至少一个活动的最大价值。分类讨论:

那么答案就是 \max f_{i,m,0/1,0/1,0/1}。时间复杂度 O(nm)。

事实上,没参加过活动的值一定是 0。所以有:

卡空间。需要滚动数组。

代码


const int N=1005,M=5005,inf=1e18;
int K,n,m,A,B;
int V[N],S[M],T[M];
int f[2][M][2][2];

il void solve(){
    memset(f,-0x3f,sizeof(f));
    K=rd,n=rd,m=rd,A=rd,B=rd;
    for(re int i=1;i<=K;++i) V[i]=rd;
    for(re int i=1;i<=n;++i) S[i]=rd;
    for(re int i=1;i<=m;++i) T[i]=rd;
    f[0][0][1][1]=0;
    int w=0,res=-inf;
    for(re int i=1;i<=n;++i){
        w^=1;
        for(re int j=0;j<=m;++j)
        for(re int x=0;x<=1;++x)
        for(re int y=0;y<=1;++y) f[w][j][x][y]=-inf;
        for(re int j=1;j<=m;++j){
            f[w][j][1][1]=max({f[w^1][j][1][1]+B,f[w][j-1][1][1]+B,f[w^1][j][0][1]+A+B,f[w][j-1][1][0]+A+B});
            f[w][j][0][1]=max({f[w][j-1][0][1]+B,f[w][j-1][0][0]+A+B});
            f[w][j][1][0]=max({f[w^1][j][1][0]+B,f[w^1][j][0][0]+A+B});
            if(S[i]==T[j]) f[w][j][0][0]=max({f[w^1][j-1][1][1],f[w^1][j-1][0][1],f[w^1][j-1][1][0],f[w^1][j-1][0][0],0ll+((j-1)?A+B*(j-1):0)})+V[T[j]];
        }
        for(re int x=0;x<=1;++x)
        for(re int y=0;y<=1;++y) res=max(res,f[w][m][x][y]);
    }
    cout<<max(res,A+B*m);
    return ;
}