CodeForces 678D Iterated Linear Function 矩阵快速幂

博客详细解析了如何使用矩阵快速幂方法解决CodeForces上的678D问题,讨论线性函数的迭代应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值