[BZOJ2875][Noi2012]隨機數生成器 && 矩陣+快速乘

注意要用快速乘就好

#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;
}


發佈了192 篇原創文章 · 獲贊 13 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章