题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5318
题面:
2 10 50 12 1213 1212 1313231 12312413 12312 4123 1231 3 131 5 50 121 123 213 132 321
86814837 797922656Hint11 111 is different with 111 11
#include <iostream> #include <cstdio> #include <cstring> #define maxn 55 #define mod 1000000007 using namespace std; int n,len[55],cnt; struct Matrix { int map[maxn][maxn]; }; //单位矩阵和计算矩阵 Matrix unit,refl; int min(int a,int b) { return a<b?a:b; } //单位矩阵 void init() { memset(unit.map,0,sizeof(unit.map)); for(int i=0;i<maxn;i++) unit.map[i][i]=1; } //矩阵乘 Matrix mult(Matrix a,Matrix b) { int i,j,k; Matrix c; for(i=0;i<cnt;i++) for(j=0;j<cnt;j++) { c.map[i][j]=0; for(k=0;k<cnt;k++) c.map[i][j]=(c.map[i][j]+1LL*a.map[i][k]*b.map[k][j])%mod; } return c; } //快速幂 Matrix quick_pow(int x) { Matrix tmp=refl,res=unit; while(x) { //二进制,取或不取 if(x&1) res=mult(res,tmp); x=x>>1; tmp=mult(tmp,tmp); } return res; } int main() { char store[55][55],temp[55][55]; int t,m,l1,l2,ans; init(); scanf("%d",&t); Matrix ansM; while(t--) { //读入 memset(refl.map,0,sizeof(refl.map)); memset(ansM.map,0,sizeof(ansM.map)); scanf("%d%d",&n,&m); cnt=0; //去重 for(int i=0;i<n;i++) { scanf("%s",temp[i]); bool sign=true; for(int j=0;j<i;j++) { if(strcmp(temp[j],temp[i])==0) { sign=false; break; } } if(sign) { int j; for(j=0;j<strlen(temp[i]);j++) { store[cnt][j]=temp[i][j]; } //这里忘记加串结束符,郁闷了我好久.... store[cnt][j]=0; cnt++; } } for(int i=0;i<cnt;i++) len[i]=strlen(store[i]); //特判 if(m==1) { printf("%d\n",cnt); continue; } //处理能否连接关系 for(int i=0;i<cnt;i++) { if(len[i]>1) { for(int j=0;j<cnt;j++) { if(len[j]>1) { if(i==j) { refl.map[i][i]=1; continue; } l1=len[i]; l2=len[j]; bool flag; for(int k=2;k<=min(l1,l2);k++) { flag=true; for(int z=1;z<=k;z++) { if(store[i][l1-z]!=store[j][k-z]) { flag=false; break; } } if(flag)break; } if(flag) refl.map[i][j]=1; } } } } m--; //快速幂 ansM=quick_pow(m); ans=0; //累加 for(int i=0;i<cnt;i++) { for(int j=0;j<cnt;j++) { ans=(ans+ansM.map[i][j])%mod; } } printf("%d\n",ans); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 5318 The Goddess Of The Moon(矩阵快速幂详解)
原文地址:http://blog.csdn.net/david_jett/article/details/47168773