Luogu P2679 子串

题目链接:Click here

Solution:

统计方案,第一时间就应该想到dp

\(f[i][j][k][0/1]\)表示在\(A\)串到第\(i\)个位置,现在要匹配\(B\)串的第\(j\)个位置,拿出了\(k\)个子串的方案

其中最后一维表示\(i\)这个位置选不选,易得初始状态\(f[i][0][0][0]=1\)

状态转移方程也十分好想:

\[f[i][j][k][0]=f[i-1][j][k][0]+f[i-1][j][k][1]\\ f[i][j][k][1]=[a[i]=b[j]]\times (f[i-1][j-1][k][1]+f[i-1][j-1][k-1][1]+f[i-1][j-1][k-1][1]) \]

第一个十分显然,第二个前一部分表示仅当\(a[i]=b[j]\)时,他才有值,否则为0

然而空间并不支持开这么大,所以我们对第一维滚动一下就好了

Code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int mod=1e9+7;
const int N=1e3+1;
const int M=201;
int n,m,K;
char s1[N],s2[M];
int f[2][N][M][2];
int read(){
    int x=0,f=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-f;ch=getchar();}
    while(isdigit(ch)){x=x*10+ch-48;ch=getchar();}
    return x*f;
}
signed main(){
    n=read(),m=read(),K=read();
    scanf("%s",s1+1);scanf("%s",s2+1);
    f[0][0][0][0]=1;
    for(int i=1;i<=n;i++){
        int ty=i&1;f[ty][0][0][0]=1;
        for(int j=1;j<=min(i,m);j++)
            for(int k=1;k<=min(j,K);k++){
                f[ty][j][k][1]=0;
                f[ty][j][k][0]=((ll)(f[ty^1][j][k][0]+f[ty^1][j][k][1]))%mod;
                if(s1[i]!=s2[j]) continue;
                f[ty][j][k][1]=((f[ty^1][j-1][k-1][1]+f[ty^1][j-1][k-1][0])%mod+f[ty^1][j-1][k][1])%mod;
            }
    }printf("%lld\n",(ll)(f[n&1][m][K][1]+f[n&1][m][K][0])%mod);
    return 0;
}
posted @ 2019-09-14 16:06  DQY_dqy  阅读(98)  评论(0编辑  收藏  举报