nyoj 301 递推求值 矩阵快速幂

nyoj 301 递推求值 矩阵快速幂

分析
初始矩阵为: ,那么需要目的矩阵就是:
然后就是构造一个变换矩阵:
然后用矩阵快速幂求解。
#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 = 3;
const int MAXM = 3;
const int MOD = 1000007;

int T, N;
LL a, b, c, f1, f2;
struct Mat {
    LL mat[MAXN][MAXN];
} E, tmat, imat;
void init() {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            E.mat[i][j] = (i == j);
        }
    }
}
Mat mat_mul(const Mat& a, const Mat& b, const int& MOD) {
    Mat ret;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            ret.mat[i][j] = 0;
            for (int k = 0; k < 3; k++) {
                ret.mat[i][j] = a.mat[i][k] * b.mat[k][j] + ret.mat[i][j];
                ret.mat[i][j] %= MOD;
            }
        }
    }
    return ret;
}
Mat mat_power(const Mat& m, int 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();
    scanf("%d", &T);
    while (T--) {
        memset(imat.mat, 0, sizeof(imat.mat));
        memset(tmat.mat, 0, sizeof(tmat.mat));
        scanf("%lld %lld %lld %lld %lld %d", &f1, &f2, &a, &b, &c, &N);
        imat.mat[0][0] = f2;
        imat.mat[1][0] = f1;
        imat.mat[2][0] = 1;
        tmat.mat[0][0] = b;
        tmat.mat[0][1] = a;
        tmat.mat[0][2] = c;
        tmat.mat[1][0] = tmat.mat[2][2] = 1;
        if (N == 1) {
            printf("%lld\n", (f1 + MOD) % MOD);
            continue;
        }
        if (N == 2) {
            printf("%lld\n", (f2 + MOD) % MOD);
            continue;
        }
        Mat ret = mat_power(tmat, N - 1, MOD);
        Mat res = mat_mul(ret, imat, MOD);
        printf("%lld\n", (res.mat[1][0] + MOD) % MOD);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值