Address: HDU 1757
Finally, the matrix will be constructed. In fact, it is not difficult, just blame yourself for being stupid .. =!
F (x) = A0 * F (x-1) + A1 * F (X-2) + A2 * F (X-3) + ...... + A9 * F (X-10)
The constructed matrix is: (The Matrix constructed in my code is reversed up and down)
| 0 1 0... 0 | f0 | F1 |
| 0 0 1 0... 0 | F1 | F2 |
| ...... 1 | * |... | = |
| A9 A8 ...... A0 | F9 | F10 |
Then, according to the combination Law of the matrix, we can first calculate the (K-9) Power of the constructed matrix. Finally, calculate the first number.
The Code is as follows:
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;int mod, a[20];struct matrix{ int ma[20][20];} init, res, s;matrix Mult(matrix x, matrix y){ int i, j, k; matrix tmp; for(i=0; i<10; i++) { for(j=0; j<10; j++) { tmp.ma[i][j]=0; for(k=0; k<10; k++) { tmp.ma[i][j]=(tmp.ma[i][j]+x.ma[i][k]*y.ma[k][j])%mod; } } } return tmp;}matrix Pow(matrix x, int k){ matrix tmp; int i, j; for(i=0; i<10; i++) for(j=0; j<10; j++) tmp.ma[i][j]=(i==j); while(k) { if(k&1) tmp=Mult(tmp,x); x=Mult(x,x); k>>=1; } return tmp;}int main(){ int k, x, i, j; while(scanf("%d%d",&k,&mod)!=EOF) { if(k<10) { printf("%d\n",k%mod); continue ; } for(i=9; i>=0; i--) { a[i]=9-i; } for(i=0; i<10; i++) { scanf("%d",&x); init.ma[0][i]=x%mod; } for(i=1; i<10; i++) { for(j=0; j<10; j++) { init.ma[i][j]=(i==j+1); } } res=Pow(init,k-9); /*for(i=0; i<10; i++) { for(j=0; j<10; j++) { printf("%d ",res.ma[i][j]); } puts(""); }*/ int ans=0; for(j=0; j<10; j++) { ans=(ans+res.ma[0][j]*a[j])%mod; //printf("%d %d %d\n",res.ma[i][j],a[i],ans); } printf("%d\n",ans); } return 0;}
HDU 1757 a simple math problem (matrix fast power)