给出一个d阶线性递推关系,求f(n) mod m的值。
,
求出An-dv0,该向量的最后一个元素就是所求。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std; const int maxn = ; typedef long long Matrix[maxn][maxn];
typedef long long Vector[maxn]; int d, n, m; void matrix_mul(Matrix A, Matrix B, Matrix res)
{
Matrix C;
memset(C, , sizeof(C));
for(int i = ; i < d; i++)
for(int j = ; j < d; j++)
for(int k = ; k < d; k++)
C[i][j] = (C[i][j] + A[i][k]*B[k][j]) % m;
memcpy(res, C, sizeof(C));
} void matrix_pow(Matrix A, int n, Matrix res)
{
Matrix a, r;
memcpy(a, A, sizeof(a));
memset(r, , sizeof(r));
for(int i = ; i < d; i++) r[i][i] = ;
while(n)
{
if(n&) matrix_mul(r, a, r);
n >>= ;
matrix_mul(a, a, a);
}
memcpy(res, r, sizeof(r));
} int main()
{
//freopen("in.txt", "r", stdin); while(cin >> d >> n >> m && d)
{
Matrix A;
memset(A, , sizeof(A));
Vector a, f;
for(int i = ; i < d; i++) { cin >> a[i]; a[i] %= m; }
for(int i = ; i < d; i++) { cin >> f[i]; f[i] %= m; }
if(n <= d) { cout << f[n-] << "\n"; continue; }
for(int i = ; i < d-; i++) A[i][i+] = ;
for(int i = ; i < d; i++) A[d-][i] = a[d-i-];
matrix_pow(A, n-d, A);
long long ans = ;
for(int i = ; i < d; i++) ans = (ans + A[d-][i]*f[i]) % m;
cout << ans << "\n";
} return ;
}
代码君