bzoj3864 Hero meet devil(ddp)

Keywords: Programming

This is probably dynamic programming, qaq

To give a string S with length <=15 (including ACGT only), for all I (0<=i<== | S |), find out how many string T with length M satisfies the longest common subsequence length of string T and string S is I.

We consider the general O(n^2)dp for lcs,f[i][j] for LCS (S[1.i], T[1.j]).
We have transfers:
f[i][j]=max(f[i][j−1],f[i−1][j],[S[i]==T[j]]∗(f[i−1][j−1]+1))
We find that the difference between f[i][j] and f[i+1][j] may only be 0 or 1, so we can subtract the difference and express f[1][j] by a state. f[n][j], the number of States is O(2n). We find that f[1] n][j] is only related to f[1... n][j-1] is relevant, so we can pre-process the string T and add a character to the new state S'.
Then we put on an outer dp:
dp[i][S] denotes the first bit matched to the string T, f[1... The n][i] state is the input number of S.
Scrolling array optimization space qaq

Complexity O(4n2n+4m2n)

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 10010
#define mod 1000000007
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int bin[16],n,m,trans[33000][4],dp[2][33000],cnt[33000],ans[20];
char ch[4]={'A','C','G','T'},a[20];
inline void predp(){
    int f[20],g[20];
    for(int S=0;S<bin[n];++S){
        memset(f,0,sizeof(f));memset(g,0,sizeof(g));
        for(int i=0;i<n;++i) f[i+1]=f[i]+(bool)(S&bin[i]);
        cnt[S]=f[n];
        for(int k=0;k<4;++k){
            for(int i=1;i<=n;++i){
                g[i]=max(g[i-1],f[i]);
                if(ch[k]==a[i]) g[i]=max(g[i],f[i-1]+1);
            }trans[S][k]=0;
            for(int i=0;i<n;++i) if(g[i+1]-g[i]) trans[S][k]|=bin[i];
        }
    }
}
int main(){
//  freopen("a.in","r",stdin);
    int tst=read();bin[0]=1;
    for(int i=1;i<=15;++i) bin[i]=bin[i-1]<<1;
    while(tst--){
        scanf("%s",a+1);n=strlen(a+1);m=read();predp();
        memset(dp[0],0,sizeof(dp[0]));int p=0;dp[p][0]=1;
        for(int i=1;i<=m;++i){
            memset(dp[p^1],0,sizeof(dp[0]));
            for(int S=0;S<bin[n];++S){
                if(!dp[p][S]) continue;
                for(int k=0;k<4;++k)
                    (dp[p^1][trans[S][k]]+=dp[p][S])%=mod;
            }p^=1;
        }memset(ans,0,sizeof(ans));
        for(int i=0;i<bin[n];++i) (ans[cnt[i]]+=dp[p][i])%=mod;
        for(int i=0;i<=n;++i) printf("%d\n",ans[i]);
    }return 0;
}

Posted by mcloan on Tue, 05 Feb 2019 16:15:16 -0800