您的位置:首页 > 其它

CodeForces 678D Iterated Linear Function 矩阵快速幂

2016-07-19 11:48 441 查看

CodeForces 678D Iterated Linear Function 矩阵快速幂

题目链接CodeForces 678D Iterated Linear Function 
题意:由递推式g(n)=Ag(n-1)+B,g(0)=X;求g(n) % (1e9+7)。
思路:构造变换矩阵A为{{A, B}, {0, 1}}; 初始矩阵B为{{X, 0}, {1, 0}}; 那么A^N*B求出答案。
#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 = 2;
const int MOD = 1e9 + 7;

int T;
LL X, A, B, N;
struct Mat {
int R, C;
LL mat[MAXN][MAXN];
Mat() {
memset(mat, 0, sizeof(mat));
}
Mat(int r, int c) : R(r), C(c) {
Mat();
}
Mat(int r, int c, LL arr[][MAXN]) {
Mat();
R = r;
C = c;
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
mat[i][j] = arr[i][j];
}
}
}
} E, tmat, imat;
void init() {
E = Mat(2, 2);
for (int i = 0; i < E.R; i++) {
for (int j = 0; j < E.C; j++) {
E.mat[i][j] = (i == j);
}
}
}
Mat mat_mul(const Mat& a, const Mat& b, const int& MOD) {
Mat ret(2, 2);
for (int i = 0; i < a.R; i++) {
for (int j = 0; j < b.C; j++) {
ret.mat[i][j] = 0;
for (int k = 0; k < a.C; k++) {
ret.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % MOD;
ret.mat[i][j] %= MOD;
}
}
}
return ret;
}
Mat mat_power(const Mat& m, LL 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();
while (~scanf("%I64d %I64d %I64d %I64d", &A, &B, &N, &X)) {
LL arr1[][MAXN] = {{A, B}, {0, 1}};
LL arr2[][MAXN] = {{X, 0}, {1, 0}};
tmat = Mat(2, 2, arr1);
imat = Mat(2, 2, arr2);
Mat res(2, 2);
res = mat_power(tmat, N, MOD);
res = mat_mul(res, imat, MOD);
printf("%I64d\n", res.mat[0][0]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: