http://acm.hdu.edu.cn/showproblem.php?pid=1757
10 9999 1 1 1 1 1 1 1 1 1 1 20 500 1 0 1 0 1 0 1 0 1 0
45 104
#include <stdio.h> #include <iostream> #include <string.h> #include <math.h> using namespace std; typedef long long LL; const int N=10; LL MOD,n; int a[10]; struct Matrix { LL m[N][N]; }; Matrix I= { 1,0,0,0,0,0,0,0,0,0, 0,1,0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,1 }; Matrix multi(Matrix a,Matrix b) { Matrix c; for(int i=0; i<N; i++) for(int j=0; j<N; j++) { c.m[i][j]=0; for(int k=0; k<N; k++) { c.m[i][j]+=a.m[i][k]*b.m[k][j]%MOD; } c.m[i][j]=c.m[i][j]%MOD; } return c; } Matrix quick_mod(Matrix a,LL k) { Matrix ans=I; while(k!=0) { if(k&1) { ans=multi(ans,a); } k>>=1; a=multi(a,a); } return ans; } int main() { while(~scanf("%I64d%I64d",&n,&MOD)) { for(int i=0;i<10;i++) scanf("%d",&a[i]); if(n<=9) { printf("%I64d\n",n); continue; } Matrix A={a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9], 1,0,0,0,0,0,0,0,0,0, 0,1,0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,1,0 }; Matrix P=quick_mod(A,n-9); LL x=(P.m[0][0]*9%MOD+P.m[0][1]*8%MOD+P.m[0][2]*7%MOD+P.m[0][3]*6%MOD+P.m[0][4]*5%MOD+P.m[0][5]*4%MOD+P.m[0][6]*3%MOD+P.m[0][7]*2%MOD+P.m[0][8])%MOD; if(x<0) x+=MOD; printf("%I64d\n",x); } return 0; }