给你一个数列的前d项 第n项(n > d) f(n) = a1 f(n - 1) + a2 f(n - 2) + a3 f(n - 3) + ... + ad f(n - d), for n > d.
n很大 可以构造一个矩阵
f(n) = A*f(n-1)
例如n=5
0 1 0 0 0 f[1] f[2] 0 0 1 0 0 f[2] f[3] 0 0 0 1 0 * f[3] = f[4] 0 0 0 0 1 f[4] f[5] a5 a4 a3 a2 a1 f[5] f[6]
f[n] = A^(n-d)*f[d];f[n] = A^(n-d)*f[d];
所以可以快速幂出A矩阵的n-d次 在乘以f[d]
#include <cstdio> #include <cstring> const int maxn = 20; struct Matrix { long long a[maxn][maxn]; }; Matrix a, c; long long b[maxn]; long long n, m; int d; Matrix matrix(Matrix x, Matrix y) { Matrix z; memset(z.a, 0, sizeof(z.a)); for(int i = 1; i <= d; i++) { for(int j = 1; j <= d; j++) { for(int k = 1; k <= d; k++) { z.a[i][j] += x.a[i][k] * y.a[k][j]; z.a[i][j] %= m; } } } return z; } void matrix_pow(long long n) { while(n) { if(n&1) c = matrix(c, a); a = matrix(a, a); n >>= 1; } } int main() { while(scanf("%d %d %d", &d, &n, &m), d || n || m) { memset(a.a, 0, sizeof(a.a)); memset(c.a, 0, sizeof(c.a)); for(int i = d; i >= 1; i--) scanf("%d", &a.a[d][i]); for(int i = 1; i <= d; i++) scanf("%d", &b[i]); for(int i = 1; i < d; i++) a.a[i][i+1] = 1; for(int i = 1; i <= d; i++) c.a[i][i] = 1; long long ans = 0; if(d < n) { matrix_pow(n-d);//n-d个矩阵a相乘存在c c初始化为单位矩阵 for(int i = 1;i <= d; i++) { ans += c.a[d][i]*b[i]; ans %= m; } } else ans = b[n]%m; printf("%d\n", ans); } return 0; } /* 1 1 100 2 1 2 10 100 1 1 1 1 3 2147483647 12345 12345678 0 12345 1 2 3 0 0 0 */