Description
Input
Output
Sample Input
2 3 aa ab 1 2 a
Sample Output
104 52思路:先用AC自动机找出状态,然后用矩阵快速幂求出不包含词根的单词个数。再求出所有的单词数,相减就可以了。失误点:L 用int 输入不能+1 否则就冒了。#include<iostream> #include<cstring> #include<cstdio> #include<queue> #define FOR(i,a,b) for(int i=a;i<=b;++i) #define clr(f,z) memset(f,z,sizeof(f)) #define LL unsigned long long using namespace std; const int msize=90; const int sig=26; class Matrix { public: LL f[37][37]; int n; Matrix(){}; Matrix(int x) { n=x; FOR(i,0,x-1)FOR(j,0,x-1) f[i][j]=0; } Matrix operator*(const Matrix&b)const { Matrix c=Matrix(n); FOR(i,0,n-1)FOR(j,0,n-1)FOR(k,0,n-1) c.f[i][j]+=f[i][k]*b.f[k][j]; return c; } void out() { FOR(i,0,n-1)FOR(j,0,n-1) printf("%llu%c",f[i][j],j==n-1?'\n':' '); } }; class AC_Machine { public: int f[msize],val[msize],ch[msize][sig],sz; void clear() { sz=1; clr(ch[0],0);val[0]=0; } int idx(char x) { return x-'a'; } void insert(char*s,int v) { int u=0,c; for(int i=0;s[i];++i) { c=idx(s[i]); if(!ch[u][c]) { clr(ch[sz],0);val[sz]=0; ch[u][c]=sz++; } u=ch[u][c]; } val[u]=v; } void getFail() { int u,v,r; queue<int>Q; FOR(c,0,sig-1) { u=ch[0][c]; if(u) { Q.push(u);f[u]=0; } } while(!Q.empty()) { r=Q.front();Q.pop(); val[r]|=val[ f[r] ]; FOR(c,0,sig-1) { u=ch[r][c]; if(!u) { ch[r][c]=ch[ f[r] ][c];continue; } Q.push(u); v=f[r]; while(v&&!ch[v][c])v=f[v]; f[u]=ch[v][c]; } } } Matrix getMatrix() { Matrix ret=Matrix(sz+1);//one more for sum FOR(i,0,sz-1)FOR(j,0,sig-1) if(!val[ ch[i][j] ]) ret.f[i][ ch[i][j] ]++; FOR(i,0,sz)ret.f[i][sz]=1; return ret; } }; Matrix M_pow(Matrix a,int m) { Matrix ret=Matrix(a.n); FOR(i,0,a.n-1) ret.f[i][i]=1; while(m) { if(m&1)ret=ret*a; a=a*a;m>>=1; } return ret; } char s[77]; AC_Machine ac; int main() { int n,m; while(~scanf("%d%d",&n,&m)) { ac.clear(); FOR(i,1,n) { scanf("%s",s); ac.insert(s,1); } ac.getFail(); Matrix ret=ac.getMatrix(); //ret.out(); ret=M_pow(ret,m); LL ans=0; FOR(i,0,ret.n-1) ans+=ret.f[0][i]; ret=Matrix(2); --ans; //初始是多加了一个 ret.f[0][0]=1;ret.f[0][1]=1; ret.f[1][0]=0;ret.f[1][1]=26; //ret.out(); ret=M_pow(ret,m); LL tans=0; tans=ret.f[0][1]+ret.f[1][1];//再推一位 --tans; ans=tans-ans; cout<<ans<<endl; //printf("%llu\n",ans); } return 0; }