题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1757
盗用一张图:
把问题转化为求矩阵的n-9次幂就行了;
直接上代码了;
View Code
1 #include<iostream> 2 #include<cstring> 3 const int N=10; 4 using namespace std; 5 int k,m; 6 struct Matrix{ 7 int map[N][N]; 8 }; 9 10 Matrix matrix; 11 12 void Initiate(){ 13 for(int i=0;i<N;i++){ 14 scanf("%d",&matrix.map[0][i]); 15 } 16 for(int i=1;i<N;i++){ 17 for(int j=0;j<N;j++){ 18 if(i==(j+1))matrix.map[i][j]=1; 19 else matrix.map[i][j]=0; 20 } 21 } 22 } 23 24 //矩阵相乘 25 Matrix Mul(Matrix &a,Matrix &b){ 26 Matrix c; 27 for(int i=0;i<N;i++){ 28 for(int j=0;j<N;j++){ 29 c.map[i][j]=0; 30 for(int k=0;k<N;k++){ 31 c.map[i][j]+=a.map[i][k]*b.map[k][j]; 32 } 33 c.map[i][j]%=m; 34 } 35 } 36 return c; 37 } 38 39 //快速幂 40 Matrix Pow(int n){ 41 Matrix t; 42 if(n==1)return matrix; 43 if(n&1)return Mul(matrix,Pow(n-1)); 44 else { 45 Matrix temp=Pow(n>>1); 46 return Mul(temp,temp); 47 } 48 } 49 50 51 int main(){ 52 while(scanf("%d%d",&k,&m)!=EOF){ 53 Initiate(); 54 if(k<10){ 55 printf("%d\n",k%m); 56 continue; 57 } 58 Matrix temp=Pow(k-9); 59 int ans=0; 60 for(int i=0;i<N;i++){ 61 ans+=temp.map[0][i]*(N-i-1); //最后要乘上f[9],f[8],...,f[1],f[0]; 62 ans%=m; 63 } 64 printf("%d\n",ans); 65 } 66 return 0; 67 }