【Portal: BZOJ1009】
Brief title:
Given n, m, k, and an unlucky string of length m, find the number of sequences in which a substring of length n does not exist as an unlucky string, and the answer is %k
answer:
God Moment Multiplier + KMP
f[i][j] means that the current enumeration reaches the i-th bit, and matches the unlucky number to the j-th bit
a[i][j] means match to the i-th bit and transfer to the j-th bit scheme number (can be calculated by KMP)
The equation of f[i+1][k]=f[i][j]*a[j][k] can obviously be worked out
Then multiply the moment to accelerate, the answer is f[n][0]+f[n][1]+...+f[n][m-1]
Reference Code:
#include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<cmath> using namespace std; int Mod; struct node { int a[21][21]; node() { memset(a,0,sizeof(a)); } }cmp,ans; int m; node chengfa (node a, node b) { node c; for(int i=0;i<m;i++) { for(int j=0;j<m;j++) { for(int k=0;k<m;k++) { c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j])%Mod; } } } return c; } node p_mod(node a,int b) { node ans; for(int i=0;i<m;i++) ans.a[i][i]=1; while(b!=0) { if (b% 2 == 1 ) ans= chengfa(ans,a); a=chengfa(a,a);b/=2; } return ans; } char st[21]; int a[21],p[21]; int main() { int n; scanf("%d%d%d",&n,&m,&Mod); scanf("%s",st+1); p[1]=0;a[1]=st[1]-'0'; for(int i=2;i<=m;i++) { a[i]=st[i]-'0'; int j=p[i-1]; while(j!=0&&a[j+1]!=a[i]) j=p[j]; if(a[j+1]==a[i]) j++; p[i]=j; } for(int i=0;i<m;i++) { for(int j=0;j<=9;j++) { int k=i; while(k!=0&&a[k+1]!=j) k=p[k]; if(a[k+1]==j) k++; cmp.a[k][i]=(cmp.a[k][i]+1)%Mod; } } cmp=p_mod(cmp,n); int ans=0; for(int i=0;i<m;i++) ans=(ans+cmp.a[i][0])%Mod; printf("%d\n",ans); return 0; }