「题解」CF222E Decoding Genome

· · 题解

> 有一些长度为 $n$ 的由 $m$ 种不同字符构成的字符串,其中有 $k$ 个约束条件,每个约束条件给定一个字符对 $(a,b)$,要求在字符串中不能有字符 $b$ 在字符 $a$ 之后出现,求满足这些约束条件的所有字符串的个数。 设 $f_{i,j}$ 为前 $i$ 个字符,第 $i$ 个字符为 $j$ 的方案数,$trans_{i,j}$ 为字符 $j$ 是否能在字符 $i$ 后面出现,有: $$f_{i,j}=\sum_{k=1}^{m}f_{i-1,k}\times trans_{k,j}$$ 时间复杂度 $O(nm^2)$,不可过。 看见这个式子很像矩阵乘法的样子,所以考虑矩阵快速幂优化,矩阵的每一位 $(i,j)$ 表示字符 $j$ 是否能在字符 $i$ 后面出现。 初始有:$f_{1,1\dots m}=1$,转移 $n-1$ 次即可,所以答案数组为: $$f_1\times trans^{n-1}$$ $\texttt{Code:}
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define rint register int
#define int long long
using namespace std;
namespace IO{
    #define File(x,y) freopen(#x,"r",stdin),freopen(#y,"w",stdout);
    inline int read(){
        int w=0,f=1; char ch=getchar();
        while(ch<'0'||ch>'9'){if(ch=='-') f=-1; ch=getchar();}
        while(ch>='0'&&ch<='9'){w=(w<<3)+(w<<1)+(ch^48); ch=getchar();}
        return w*f;
    }
    inline void write(int x){
        static int sta[35]; int top=0;
        do{sta[++top]=x%10,x/=10;}while(x);
        while(top) putchar(sta[top--]+48); puts("");
    }
}
using namespace IO;
namespace CL{
    #define fill(x,y) memset(x,y,sizeof(x))
    #define copy(x,y) memcpy(y,x,sizeof(x))

    const int maxn=60,mod=1e9+7;

    int n,m,k,ans;
    char s[2];
    namespace Matrix{
        struct matrix{
            int p[maxn][maxn];
            matrix(){fill(p,0);}
            inline void build(){for(int i=1;i<=55;i++) p[i][i]=1;}
            matrix operator *(const matrix &x)const{
                matrix res;
                for(int i=1;i<=55;i++)
                    for(int j=1;j<=55;j++)
                        for(int k=1;k<=55;k++)
                            res.p[i][j]=(res.p[i][j]+1ll*p[i][k]*x.p[k][j]%mod)%mod;
                return res;
            }
        }trans,f;
        matrix qpow(matrix x,int y){
            matrix res; res.build();
            while(y){
                if(y&1) res=res*x;
                x=x*x;
                y>>=1;
            }
            return res;
        }
    }using namespace Matrix;
    inline int id(char x){
        if(x>='a' && x<='z') return x-96;
        if(x>='A' && x<='Z') return x-38;
    }

    inline int main(){
        n=read(); m=read(); k=read();
        for(int i=1;i<=m;i++)
            for(int j=1;j<=m;j++)
                trans.p[i][j]=1;
        for(int i=1;i<=k;i++){
            scanf("%s",s);
            trans.p[id(s[0])][id(s[1])]=0;
        }
        for(int i=1;i<=m;i++) f.p[1][i]=1;
        trans=qpow(trans,n-1);
        f=f*trans;
        for(int i=1;i<=m;i++) ans=(ans+f.p[1][i])%mod;
        printf("%lld\n",ans);
        return 0;
    }
}
signed main(){return CL::main();}