题解 P1349 【广义斐波那契数列】
更好的阅读体验
Solution
基本斐波那契数列矩阵是
广义斐波那契数列矩阵是
那么要求的就是:
然后就可以用矩阵快速幂来解决了。
Code
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long LL;
struct Matrix {
LL a[2][2];
inline void clear() {//矩阵清空
memset(a, 0, sizeof(a));
}
inline void init() {//单位矩阵
memset(a, 0, sizeof(a));
for (int i = 0; i < 2; i++)
a[i][i] = 1;
}
};
LL n, p, q, a1, a2, mod;
Matrix F, a, ans;
inline LL Plus(LL x, LL y) {
x += y;
if (x >= mod) x -= mod;
return x;
}
inline LL power(LL x, LL y) {//快速幂
LL ret = 0;
while (y) {
if (y & 1) ret = (ret + x) % mod;
x = (x + x) % mod;
y >>= 1;
}
return ret;
}
Matrix operator * (Matrix a, Matrix b) {//矩阵乘法
Matrix ret;
ret.clear();
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
ret.a[i][j] = Plus(ret.a[i][j] % mod, power(a.a[i][k], b.a[k][j])% mod) % mod;
return ret;
}
inline Matrix Matrix_Power(Matrix a, LL x) {//矩阵快速幂
Matrix ret;
ret.init();
while (x) {
if (x & 1) ret = ret * a;
x >>= 1;
a = a * a;
}
return ret;
}
int main() {
scanf("%lld%lld%lld%lld%lld%lld", &q, &p, &a1, &a2, &n, &mod);
F.a[0][0] = a1, F.a[0][1] = a2;
a.a[0][0] = 0, a.a[1][0] = 1, a.a[0][1] = p; a.a[1][1] = q;
ans = F * Matrix_Power(a, n - 2);
printf("%lld\n", ans.a[0][1] % mod);
return 0;
}