[BZOJ2875][Noi2012]随机数生成器 && 矩阵+快速乘

本文介绍了一种利用快速幂进行矩阵乘法的方法,并通过一个具体的C++代码示例展示了如何求解特定线性同余方程组的问题。该方法适用于高效计算大规模线性同余序列的第n项。

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

注意要用快速乘就好

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
#define SF scanf
#define PF printf
using namespace std;
typedef long long LL;
const int MAXN = 3;
LL MOD, g, c, a, n, x0;
LL mul_mod(LL x, LL k) {
    LL ret = 0;
    while(k) {
        if(k & 1) ret = (ret + x) % MOD;
        x = (x << 1) % MOD;
        k >>= 1;
    }
    return ret;
}
struct Matrix {
    int r, c;
    LL a[MAXN+2][MAXN+2];
    Matrix () {
        r = c = 0;
        memset(a, 0, sizeof(a));
    }
    LL * operator [] (const int &x) { 
        return a[x];
    }
    void set(int n) {
        for(int i = 0; i < n; i++) a[i][i] = 1;
        r = c = n;
    }
    Matrix operator * (const Matrix &t) const {
        Matrix ret;
        ret.r = r; ret.c = t.c;
        for(int i = 0; i < r; i++)
            for(int k = 0; k < c; k++)
                for(int j = 0; j < t.c; j++) 
                    ret[i][j] = (ret[i][j] + mul_mod(a[i][k], t.a[k][j])) % MOD;
        return ret;
    }
} A, B;
Matrix pow_mod(Matrix x, LL k) {
    Matrix ret; 
    ret.set(x.r);
    while(k) {
        if(k & 1) ret = ret * x;
        x = x * x;
        k >>= 1;
    }
    return ret;
}
int main() {
    cin >> MOD >> a >> c >> x0 >> n >> g;
    A.r = A.c = 2;
    B.r = 1; B.c = 2;
    A[0][0] = A[0][1] = 1; A[1][1] = a;
    B[0][0] = c; B[0][1] = x0;
    Matrix t = pow_mod(A, n);
    Matrix ans = B * t;
    cout << ans[0][1] % g;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值