HDU 4686 Arc of Dream (矩阵快速幂)

题目链接

这题要两个相乘再求和,因此在矩阵中加一行来表示每一次累加的结果。具体看递推式吧。


代码:这题一样的写法,java超时。。。C++语法不是很熟,矩阵的结构体照着别人的模式写下来的

#include <iostream>
#include <cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

typedef __int64 int64;
const int64 mod = 1000000007;
int64 n, A0, AX, AY, B0, BX, BY;
struct Matrix{
    int64 mat[5][5];
    Matrix operator * (const Matrix &b) const {
        Matrix tmp;
        for(int i = 0; i < 5; i++) {
            for(int j = 0; j < 5; j++) {
                    tmp.mat[i][j] = 0;
                for(int k = 0; k < 5; k++) {
                    tmp.mat[i][j] += (mat[i][k]%mod * b.mat[k][j]%mod) % mod;
                    tmp.mat[i][j] %= mod;
                }
            }
        }
        return tmp;
    }
};

void pow(int64 k, Matrix &a) {
        if(k == 0) {cout<< 0 << endl; return;}
        Matrix res;
        memset(res.mat, 0, sizeof(res.mat));
        for(int i = 0; i < 5; i++) {
            res.mat[i][i] = 1;
        }
        while(k > 0) {
            if(1&k) {
                res = res * a;
            }
            a = a * a;
            k >>= 1;
        }
        int64 sum = 0;
        sum += (A0%mod) * res.mat[3][0];
        sum %= mod;
        sum += (B0%mod) * res.mat[3][1];
        sum %= mod;
        sum += (A0 * B0%mod)%mod * res.mat[3][2];
        sum %= mod;
        sum += res.mat[3][4]%mod;
        sum %= mod;
        cout << sum << endl;
    }

int main(){
    while(scanf("%I64d" , &n) != EOF) {
            scanf("%I64d%I64d%I64d" , &A0, &AX , &AY);
            scanf("%I64d%I64d%I64d" , &B0, &BX, &BY);
            Matrix matrix;
            memset(matrix.mat, 0, sizeof(matrix.mat));
            matrix.mat[0][0] = AX%mod; matrix.mat[0][4] = AY%mod;
            matrix.mat[1][1] = BX%mod; matrix.mat[1][4] = BY%mod;
            matrix.mat[2][0] = ((AX%mod)*(BY%mod))%mod;
            matrix.mat[2][1] = ((AY%mod)*(BX%mod))%mod;
            matrix.mat[2][2] = ((AX%mod)*(BX%mod))%mod;
            matrix.mat[2][4] = ((AY%mod)*(BY%mod))%mod;
            matrix.mat[3][2] = 1; matrix.mat[3][3] = 1;
            matrix.mat[4][4] = 1;
            pow(n, matrix);
        }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值