代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
using ll = unsigned long long;
const int kMaxN = -1, kInf = (((1 << 30) - 1) << 1) + 1, kMod = 1e9 + 7;
ll n, a1, a2, x, y;
struct matrix {
ll n, m, mtx[22][22];
} a, b, ans;
void clr(matrix base) {
memset(base.mtx, 0, sizeof base.mtx);
}
void init() { // 初始化 base 矩阵
a.n = a.m = 4;
b.n = 4, b.m = 1;
a.mtx[1][1] = a.mtx[1][2] = a.mtx[3][2] = 1;
a.mtx[2][2] = x * x % kMod;
a.mtx[2][3] = y * y % kMod;
a.mtx[2][4] = ((x * y) << 1) % kMod;
a.mtx[4][2] = x;
a.mtx[4][4] = y;
b.mtx[1][1] = b.mtx[3][1] = a1 * a1 % kMod;
b.mtx[2][1] = a2 * a2 % kMod;
b.mtx[4][1] = a2 * a1 % kMod;
}
matrix mul(matrix a, matrix b) { // 矩阵乘法
matrix res;
clr(res);
res.n = a.n, res.m = b.m;
for (int i = 1; i <= a.n; ++ i) {
for (int j = 1; j <= a.m; ++ j) {
for (int k = 1; k <= b.m; ++ k) {
res.mtx[i][j] = (res.mtx[i][j] + a.mtx[i][k] * b.mtx[k][j]) % kMod;
}
}
}
return res;
}
void qpow(matrix a, ll n) {
ans = a;
for (; n; n >>= 1) {
if (n & 1) {
ans = mul(ans, a);
}
a = mul(a, a);
}
}
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t;
for (cin >> t; t; -- t) {
clr(a), clr(b), clr(ans);
cin >> n >> a1 >> a2 >> x >> y;
a1 %= kMod, a2 %= kMod, x %= kMod, y %= kMod;
if (n == 1) {
cout << a1 * a1 % kMod << '\n';
continue;
}
init();
qpow(a, n - 2);
ans = mul(ans, b);
cout << ans.mtx[1][1] << '\n';
}
return 0;
}