Give a recursive relationship that allows you to find the nth item in the relationship
It is common to think that recursion with large data can consider using matrix fast power
Here the matrix is no longer described, there is a petition
The code is as follows:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAXN usi
NG namespace Std;
int X[MAXN];
int MOD, n, D; struct Matrix {int M[MAXN][MAXN];}
A, F;
Matrix Mul (Matrix A, matrix B) {matrix res;
for (int i=1, i<=d; ++i) {for (int j=1; j<=d; ++j) {res.m[i][j] = 0;
for (int k=1; k<=d; ++k) {res.m[i][j] = (res.m[i][j]+a.m[i][k]*b.m[k][j]%mod+mod)%mod;
}}} return res;
} Matrix Pow (matrix A, int b) {Matrix res;
memset (res.m, 0, sizeof (RES.M));
for (int i=1; i<=d; ++i) res.m[i][i] = 1;
while (b) {if (b & 1) res = Mul (res, a);
A = Mul (A, a);
b >>= 1;
} return res; } int main (void) {while (~scanf ("%d%d%d", &d, &n, &mod) && (d| | n| |
MOD) {memset (a.m., 0, sizeof (a.m.));
memset (f.m, 0, sizeof (F.M)); for (int i=1; i≪=d;
++i) scanf ("%d", &x[i]);
for (int i=1; i<d; ++i) a.m[i][i+1] = 1;
for (int i=1; i<=d; ++i) {a.m[d][i] = X[d-i+1]%mod;
} for (int i=1; i<=d; ++i) {scanf ("%d", &f.m[i][1]);
F.M[I][1]%= MOD;
} Matrix tmp = Pow (A, n-d);
Matrix ans = Mul (tmp, F);
printf ("%d\n", (ans.m[d][1]+mod)%mod);
} return 0; }