这题要两个相乘再求和,因此在矩阵中加一行来表示每一次累加的结果。具体看递推式吧。
代码:这题一样的写法,java超时。。。C++语法不是很熟,矩阵的结构体照着别人的模式写下来的
#include <iostream>
#include <cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef __int64 int64;
const int64 mod = 1000000007;
int64 n, A0, AX, AY, B0, BX, BY;
struct Matrix{
int64 mat[5][5];
Matrix operator * (const Matrix &b) const {
Matrix tmp;
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
tmp.mat[i][j] = 0;
for(int k = 0; k < 5; k++) {
tmp.mat[i][j] += (mat[i][k]%mod * b.mat[k][j]%mod) % mod;
tmp.mat[i][j] %= mod;
}
}
}
return tmp;
}
};
void pow(int64 k, Matrix &a) {
if(k == 0) {cout<< 0 << endl; return;}
Matrix res;
memset(res.mat, 0, sizeof(res.mat));
for(int i = 0; i < 5; i++) {
res.mat[i][i] = 1;
}
while(k > 0) {
if(1&k) {
res = res * a;
}
a = a * a;
k >>= 1;
}
int64 sum = 0;
sum += (A0%mod) * res.mat[3][0];
sum %= mod;
sum += (B0%mod) * res.mat[3][1];
sum %= mod;
sum += (A0 * B0%mod)%mod * res.mat[3][2];
sum %= mod;
sum += res.mat[3][4]%mod;
sum %= mod;
cout << sum << endl;
}
int main(){
while(scanf("%I64d" , &n) != EOF) {
scanf("%I64d%I64d%I64d" , &A0, &AX , &AY);
scanf("%I64d%I64d%I64d" , &B0, &BX, &BY);
Matrix matrix;
memset(matrix.mat, 0, sizeof(matrix.mat));
matrix.mat[0][0] = AX%mod; matrix.mat[0][4] = AY%mod;
matrix.mat[1][1] = BX%mod; matrix.mat[1][4] = BY%mod;
matrix.mat[2][0] = ((AX%mod)*(BY%mod))%mod;
matrix.mat[2][1] = ((AY%mod)*(BX%mod))%mod;
matrix.mat[2][2] = ((AX%mod)*(BX%mod))%mod;
matrix.mat[2][4] = ((AY%mod)*(BY%mod))%mod;
matrix.mat[3][2] = 1; matrix.mat[3][3] = 1;
matrix.mat[4][4] = 1;
pow(n, matrix);
}
return 0;
}