题意:f(n) = a1f(n − 1) + a2f(n − 2) + a3f(n − 3) + . . . + adf(n − d), for n > d,求f (n) % m。训练指南的题目
分析:令:,.则
#include <bits/stdc++.h> int d, n, m; int a[16], f[16]; struct Mat { int m[17][17]; int row, col; Mat() { //row = col = 16; memset (m, 0, sizeof (m)); } void init(int sz) { row = col = sz; for (int i=1; i<row; ++i) { m[i][i+1] = 1; } int c = sz - 1; for (int i=2; i<=col; ++i) { m[sz][i] = a[c--]; } } void change(int sz) { row = col = sz; for (int i=1; i<=sz; ++i) { m[i][i] = 1; } } }; Mat operator * (const Mat &a, const Mat &b) { Mat ret; ret.row = a.row; ret.col = b.col; for (int i=1; i<=a.row; ++i) { for (int j=1; j<=b.col; ++j) { for (int k=1; k<=a.col; ++k) { int &r = ret.m[i][j]; r = (r + 1ll * a.m[i][k] * b.m[k][j]) % m; } } } return ret; } Mat operator ^ (Mat x, int n) { Mat ret; ret.change (d+1); while (n) { if (n & 1) { ret = ret * x; } x = x * x; n >>= 1; } return ret; } //Running_Time int main() { while (scanf ("%d%d%d", &d, &n, &m) == 3) { if (!d && !n && !m) { break; } for (int i=1; i<=d; ++i) { scanf ("%d", a+i); } for (int i=1; i<=d; ++i) { scanf ("%d", f+i); } if (n <= d) { printf ("%d ", f[n] % m); } else { Mat ans, Fd; ans.init (d + 1); ans = ans ^ (n - d); Fd.row = d + 1; Fd.col = 1; for (int i=2; i<=d+1; ++i) { Fd.m[i][1] = f[i-1]; } ans = ans * Fd; printf ("%d ", ans.m[d+1][1]); } } return 0; }