思路:构造矩阵+矩阵快速幂
分析:
1 题目给定f(n)的表达式 f(n) = a1 f(n - 1) + a2 f(n - 2) + a3 f(n -3) + ... + ad f(n - d)对于n > d的时候
2 那么我们可以构造出矩阵
a1 a2 ... an f(n-1) f(n)
1 0 ......... 0 f(n-2) f(n-1)
0 1 ..........0 * ........ => ......
.................. ....... ......
0 0 ...... 1 0 ....... f(n-d)
0 0 0 0 ... 0 f(n-d) f(n-d+1)
3 题目有个地方错了,两个case之间根本不需要空行
代码:
/************************************************ * By: chenguolin * * Date: 2013-08-29 * * Address: http://blog.csdn.net/chenguolinblog * ************************************************/ #include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; typedef long long int64; const int N = 16; int d , n , MOD; int a[N] , f[N]; struct Matrix{ int64 mat[N][N]; Matrix operator*(const Matrix &m)const{ Matrix tmp; for(int i = 0 ; i < d ; i++){ for(int j = 0 ; j < d ; j++){ tmp.mat[i][j] = 0; for(int k = 0 ; k < d ; k++) tmp.mat[i][j] += mat[i][k]*m.mat[k][j]%MOD; tmp.mat[i][j] %= MOD; } } return tmp; } }; void init(Matrix &m){ memset(m.mat , 0 , sizeof(m.mat)); for(int i = 0 ; i < d ; i++) m.mat[0][i] = a[i+1]; for(int i = 1 ; i < d ; i++) m.mat[i][i-1] = 1; } int Pow(Matrix &m){ if(n <= d) return f[n]; n -= d; Matrix ans; memset(ans.mat , 0 , sizeof(ans.mat)); for(int i = 0 ; i < d ; i++) ans.mat[i][i] = 1; while(n){ if(n&1) ans = ans*m; n >>= 1; m = m*m; } int64 sum = 0; for(int i = 0 ; i < d ; i++) sum += ans.mat[0][i]*f[d-i]%MOD; return sum%MOD; } int main(){ Matrix m; bool isFirst = true; while(scanf("%d%d%d" ,&d , &n , &MOD) && d+n+MOD){ if(isFirst) isFirst = false; else puts(""); for(int i = 1 ; i <= d ; i++){ scanf("%d" , &a[i]); a[i] %= MOD; } for(int i = 1 ; i <= d ; i++){ scanf("%d" , &f[i]); f[i] %= MOD; } init(m); printf("%d\n" , Pow(m)); } return 0; }