Give you a sequence of the first d items nth (n > D) f (n) = A1 f (n-1) + A2 f (n-2) + A3 f (n-3) + ... + ad f (n-d), for n > D.
n Very large can construct a matrix
F (n) = A*f (n-1)
such as 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];
So you can quickly power out the n-d times of a matrix multiplied by 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, &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;
A long long ans = 0; if (d < n) {Matrix_pow (n-d);//n-d momentArray A is multiplied by the presence of C C initialized to the unit matrix 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 *