fudq and Math
描述
fudq is thinking about a simple function f(x). If x < 10 f(x) = x. If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10); Now, fudq will give you a0 ~ a9 and two positive integers k and m ,and could you help fudq to caculate f(k)%m.
输入
The problem contains mutiple test cases.Please process to the end of file. In each case, there will be two lines. In the first line , there are two positive integers k and m. ( 0 < k < 2*10^9 , 0 < m < 10^5 ) In the second line , there are ten integers represent a0 ~ a9.(0 <= ai(0<=i<=9) <= 10)
输出
For each case, output f(k) % m in one line.
样例输入
10 9999 1 1 1 1 1 1 1 1 1 1 20 500 1 5 2 0 8 2 9 0 3 0
样例输出
45 460
//矩阵快速幂运算;
#include <stdio.h> #include <string.h> #include <math.h> #define N 10 int ff[11]; int k,m;//k次方 对m取余; struct Matrix{ int v[N][N]; }; Matrix f,p; Matrix Mat_mul(Matrix m1,Matrix m2,int pri) //矩阵相乘 { Matrix c; for(int i=0;i<N;i++) for(int j=0;j<N;j++) c.v[i][j]=0; for(int i=0;i<N;i++) for(int j=0;j<N;j++) for(int k=0;k<N;k++) c.v[i][j]=(c.v[i][j]+(m1.v[i][k]*m2.v[k][j])%pri)%pri; return c; } Matrix Mpow(Matrix A,int n,int pri) //矩阵快速幂 { Matrix c,x; for(int i=0;i<N;i++) for(int j=0;j<N;j++) c.v[i][j]=0; x=A; for(int i=0;i<N;i++) c.v[i][i]=1;//单位矩阵; while(n >= 1) { if(n & 1) c=Mat_mul(c,x,pri); n=n/2; x=Mat_mul(x,x,pri); } return c; } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int i,j,k,t; while(scanf("%d %d",&k,&m)!=EOF){ int num=0; for(i=0;i<10;i++) scanf("%d",&ff[i]); for(i=0;i<10;i++) for(j=0;j<10;j++) f.v[i][j]=0; //for(i=0;i<10;i++) f1[i][i]=1; //f1为初始化的标准数组; for(i=0;i<10;i++) p.v[i][0]=ff[i]; for(i=0;i<9;i++) p.v[i][i+1]=1; if(k<10) printf("%d\n",k%m); else{ f=Mpow(p,k-9,m); //f的次方 num=0; for(i=0;i<10;i++){ num=(num+(9-i)*f.v[i][0])%m; } printf("%d\n",num); } } return 0; }