nyoj 301 递推求值 矩阵快速幂
题目链接:
nyoj 301 递推求值 矩阵快速幂
分析:
初始矩阵为:
,那么需要目的矩阵就是:
;
然后就是构造一个变换矩阵:
;
然后用矩阵快速幂求解。
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
// typedef __int64 LL;
typedef long long LL;
typedef unsigned int uint;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int MAXN = 3;
const int MAXM = 3;
const int MOD = 1000007;
int T, N;
LL a, b, c, f1, f2;
struct Mat {
LL mat[MAXN][MAXN];
} E, tmat, imat;
void init() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
E.mat[i][j] = (i == j);
}
}
}
Mat mat_mul(const Mat& a, const Mat& b, const int& MOD) {
Mat ret;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
ret.mat[i][j] = 0;
for (int k = 0; k < 3; k++) {
ret.mat[i][j] = a.mat[i][k] * b.mat[k][j] + ret.mat[i][j];
ret.mat[i][j] %= MOD;
}
}
}
return ret;
}
Mat mat_power(const Mat& m, int y, const int& MOD) {
Mat x = m, ret = E;
while (y) {
if (y & 1) ret = mat_mul(ret, x, MOD);
x = mat_mul(x, x, MOD);
y >>= 1;
}
return ret;
}
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
init();
scanf("%d", &T);
while (T--) {
memset(imat.mat, 0, sizeof(imat.mat));
memset(tmat.mat, 0, sizeof(tmat.mat));
scanf("%lld %lld %lld %lld %lld %d", &f1, &f2, &a, &b, &c, &N);
imat.mat[0][0] = f2;
imat.mat[1][0] = f1;
imat.mat[2][0] = 1;
tmat.mat[0][0] = b;
tmat.mat[0][1] = a;
tmat.mat[0][2] = c;
tmat.mat[1][0] = tmat.mat[2][2] = 1;
if (N == 1) {
printf("%lld\n", (f1 + MOD) % MOD);
continue;
}
if (N == 2) {
printf("%lld\n", (f2 + MOD) % MOD);
continue;
}
Mat ret = mat_power(tmat, N - 1, MOD);
Mat res = mat_mul(ret, imat, MOD);
printf("%lld\n", (res.mat[1][0] + MOD) % MOD);
}
return 0;
}