bzoj1009 [HNOI2008]GT考试

用a[i][j]表示  匹配到i  转移到  匹配到j 的方案数

用矩阵快速幂求解

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<string>
 7 #include<cmath>
 8 #include<ctime>
 9 #include<queue>
10 #include<stack>
11 #include<map>
12 #include<set>
13 #define rre(i,r,l) for(int i=(r);i>=(l);i--)
14 #define re(i,l,r) for(int i=(l);i<=(r);i++)
15 #define Clear(a,b) memset(a,b,sizeof(a))
16 #define inout(x) printf("%d",(x))
17 #define douin(x) scanf("%lf",&x)
18 #define strin(x) scanf("%s",(x))
19 #define LLin(x) scanf("%lld",&x)
20 #define op operator
21 #define CSC main
22 typedef unsigned long long ULL;
23 typedef const int cint;
24 typedef long long LL;
25 using namespace std;
26 void inin(int &ret)
27 {
28     ret=0;int f=0;char ch=getchar();
29     while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();}
30     while(ch>='0'&&ch<='9')ret*=10,ret+=ch-'0',ch=getchar();
31     ret=f?-ret:ret;
32 }
33 int n,m,mod,pre[100];
34 struct M
35 {
36     int a[25][25];
37     int* op [] (int x){return x[a];}
38     M(){Clear(a,0);}
39     void in(int x)
40     {
41         re(i,0,25)re(j,0,25)if(i==j)a[i][j]=1;
42     }
43     M op * (M &rhs)
44     {
45         M c;
46         re(i,0,m-1)re(j,0,m-1)re(k,0,m-1)
47             (c[i][j]+=a[i][k]*rhs[k][j])%=mod;
48         return c;
49     }
50 };
51 char s[100];
52 M qpow(M a,int b)
53 {
54     M ret;ret.in(1);
55     while(b)
56     {
57         if(b&1)ret=ret*a;
58         b>>=1;a=a*a;
59     }
60     return ret;
61 }
62 M a;
63 void kmp()
64 {
65     int k=0;
66     re(i,2,m)
67     {
68         while(k&&s[i]!=s[k+1])k=pre[k];
69         if(s[k+1]==s[i])k++;
70         pre[i]=k;
71     }
72     re(i,0,m-1)re(j,0,9)
73     {
74         int x=i;
75         while(x&&s[x+1]-'0'!=j)x=pre[x];
76         if(j==s[x+1]-'0')a[i][x+1]++;
77         else a[i][0]++;
78     }
79 }
80 int CSC()
81 {
82     inin(n),inin(m),inin(mod);
83     strin(s+1);
84     kmp();
85     M f=qpow(a,n);
86     int ans=0;
87     re(i,0,m-1)ans=(ans+f[0][i])%mod;
88     printf("%d",ans);
89     return 0;
90 }

 

posted @ 2016-02-25 11:09  HugeGun  阅读(194)  评论(0编辑  收藏  举报