1009: [HNOI2008]GT考试
Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 2734 Solved: 1684
[ Submit][ Status][ Discuss]
Description
阿申准备报名参加GT考试,准考证号为N位数X1X2....Xn(0<=Xi<=9),他不希望准考证号上出现不吉利的数字。
他的不吉利数学A1A2...Am(0<=Ai<=9)有M位,不出现是指X1X2...Xn中没有恰好一段等于A1A2...Am. A1和X1可以为
0
Input
第一行输入N,M,K.接下来一行输入M位的数。 N<=10^9,M<=20,K<=1000
Output
阿申想知道不出现不吉利数字的号码有多少种,输出模K取余的结果.
Sample Input
111
Sample Output
81
解题思路:先用KMP构造出矩形(脑子抽了)然后直接矩阵快速幂
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int n,m,maxn;
int b[21][21],c[21][21],a[21][21];
int zan[21][21];
int fa[21];
inline int read()
{
char y; int x=0,f=1; y=getchar();
while (y<'0' ||y>'9') {if (y=='-') f=-1; y=getchar();}
while (y>='0' && y<='9') {x=x*10+int(y)-48; y=getchar();}
return x*f;
}
void solve()
{
int len=n-1;
while (len>0)
{
if (len%2==1)
{
for (int i=1;i<=m;++i)
for (int j=1;j<=m;++j)
{
int sum=0;
for (int k=1;k<=m;++k)
sum=(sum+b[i][k]*c[k][j])%maxn;
zan[i][j]=sum;
}
for (int i=1;i<=m;++i)
for (int j=1;j<=m;++j)
b[i][j]=zan[i][j];
}
len=len/2;
for (int i=1;i<=m;++i)
for (int j=1;j<=m;++j)
{
int sum=0;
for (int k=1;k<=m;++k)
sum=(sum+c[i][k]*c[k][j])%maxn;
zan[i][j]=sum;
}
for (int i=1;i<=m;++i)
for (int j=1;j<=m;++j)
c[i][j]=zan[i][j];
}
}
int main()
{
n=read(); m=read(); maxn=read();
char s[25]; scanf("%s",s+1);
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
a[1][1]=1; fa[1]=0;
for (int i=2;i<=m;++i)
{
int u=fa[i-1];
while (s[u+1]!=s[i] && u!=0) u=fa[u];
if (s[u+1]!=s[i]) fa[i]=0;else
fa[i]=u+1;
}
for (int i=1;i<=m;++i)
{
if (i!=m)
{
++b[i][i+1]; ++c[i][i+1]; b[i][i+1]%=maxn; c[i][i+1]%=maxn;
}
char u=s[i];
for (char j='0';j<='9';++j)
if (u!=j)
{
int uh=fa[i-1];
while (uh!=0 && s[uh+1]!=j) uh=fa[uh];
if (s[uh+1]!=j) b[i][uh+1]=(b[i][uh+1]+1)%maxn,c[i][uh+1]=(c[i][uh+1]+1)%maxn;else
b[i][uh+2]=(b[i][uh+2]+1)%maxn,c[i][uh+2]=(c[i][uh+2]+1)%maxn;
}
}
solve();
int ans=0;
for (int i=1;i<=m;++i)
for (int j=1;j<=m;++j)
ans=(ans+a[1][i]*b[i][j])%maxn;
printf("%d",ans);
}