HDU 5667 矩阵快速幂 + 费马小定理 + 快速幂

题解

  1. 看完题目第一反应, 矩阵快速幂, 但是乘法无法构造递推
  2. 想到幂的乘法可以转成指数的加法
  3. 设f[n] = ap[n],则n > 2时 f[n] = abf[n-1]c f[n-2]=>
    p[n] = b + p[n - 1] * c + p[n - 2]就可以构造矩阵了且p[1] = 0, p[2] = b
  4. 构造矩阵
    p[2]00p[1]00b00c11100001n2=p[n]00p[n1]00b00
  5. 根据费马小定理, f[n] % p = ap[n] % p = ap[n] % (p - 1) % p
  6. 然后用快速幂求解即可, 不过要判断一种特殊情况a % p == 0此时解为0(n > 2)时, 代码中把这种情况写在费马小定理中特判, 想了一下不是很好, 不过不影响此题答案

code

#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;

ll n, a, b, c, p, up;
/**矩阵*/
struct Matrix{
    ll mat[3][3];

    void clr();
    void E();
    Matrix operator * (Matrix b);
    Matrix operator ^ (ll b);
};

void Matrix::clr(){
    memset(mat, 0, sizeof mat);
}

void Matrix::E(){
    clr();
    for(int i = 0; i < 3; ++i) mat[i][i] = 1;
}

Matrix Matrix::operator*( Matrix b){
    Matrix res;
    res.clr();

    for(int i = 0; i < 3; ++i)
        for(int j = 0; j < 3; ++j)
            for(int k = 0; k < 3; ++k)
                res.mat[i][j] = (res.mat[i][j] + mat[i][k] * b.mat[k][j]) % (p - 1);

    return res;
}

Matrix Matrix::operator^(ll b){
    Matrix res, tmp;
    res.E();
    memcpy(tmp.mat, mat, sizeof mat);

    while(b){
        if(b & 1) res = res * tmp;
        tmp = tmp * tmp;
        b >>= 1;
    }

    return res;
}

inline void input(){
    cin >> n >> a >> b >> c >> p;
}
/**快速幂*/
ll fastPowMod(ll a, ll b){
    ll res = 1;

    while(b){
        if(b & 1) res = res * a % p;
        a = a * a % p;
        b >>= 1;
    }

    return res;
}

int main(){

    int t;
    cin >> t;

    while(t--){
        input();
        if(n == 1) up = 0;
        if(n == 2) up = b;
        else{
            Matrix tmp, res;
            res.clr();
            tmp.clr();/**底数矩阵tmp, 结果矩阵res*/
            res.mat[0][0] = res.mat[0][2] = b;
            tmp.mat[0][0] = c;
            tmp.mat[0][1] = 1;
            tmp.mat[1][0] = 1;
            tmp.mat[2][0] = 1;
            tmp.mat[2][2] = 1;
            res = res * (tmp ^ (n - 2));
            up = res.mat[0][0];
            if(up == 0 && a % p == 0) up = 1;/**特判*/
        }
        ll ans = fastPowMod(a, up);
        cout << ans << endl;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值