标签:
题意:计算f(n)
f(n) = a1 f(n - 1) + a2 f(n - 2) + a3 f(n - 3) + … + ad f(n - d), for n > d.
题解:斐波那契的变形,把2个扩大成d个,然后加了a1…ad的参数,构造矩阵直接矩阵快速幂计算。
#include <stdio.h>
#include <string.h>
const int N = 20;
struct Mat {
long long g[N][N];
}res, ori;
long long d, n, m;
Mat multiply(Mat x, Mat y) {
Mat temp;
for (int i = 0; i < d; i++)
for (int j = 0; j < d; j++) {
temp.g[i][j] = 0;
for (int k = 0; k < d; k++)
temp.g[i][j] = (temp.g[i][j] + x.g[i][k] * y.g[k][j]) % m;
}
return temp;
}
void calc(long long n) {
while (n) {
if (n & 1)
ori = multiply(ori, res);
n >>= 1;
res = multiply(res, res);
}
}
int main() {
while (scanf("%lld%lld%lld", &d, &n, &m) && d + n + m) {
memset(res.g, 0, sizeof(res.g));
memset(ori.g, 0, sizeof(ori.g));
for (int i = 0; i < d; i++) {
scanf("%lld", &res.g[i][0]);
res.g[i][0] %= m;
if (i > 0)
res.g[i - 1][i] = 1;
}
for (int i = 0; i < d; i++) {
scanf("%lld", &ori.g[0][d - 1 - i]);
ori.g[0][d - 1 - i] %= m;
}
calc(n - d);
printf("%lld\n", ori.g[0][0]);
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/hyczms/article/details/46242151