模版--矩阵快速幂

矩阵快速幂


矩阵快速幂就是快速幂的矩阵用法

ll Fast_Power(ll FP_a , ll FP_n , ll FP_p) {
    ///快速幂计算 a^n mod p
    ll ret = 1 , A = FP_a;
    while(FP_n) {
        if (FP_n & 1)
            ret = ( ret * A ) % FP_p;
        A = ( A * A ) % FP_p;
        FP_n >>= 1;
    }
    return ret;
}

得到递推公式后推出转移矩阵然后就套模版啦

#include <iostream>
#include <cstdio>
#define mod 1000000009
#define ll long long
using namespace std;
struct matrix {
    ll mat[2][2];
};
matrix unit_matrix = {1, 0, 0, 1}; //单位矩阵
matrix mul(matrix a, matrix b) {
    matrix res;
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++) {
            res.mat[i][j] = 0;
            for (int k = 0; k < 2; k++) {
                res.mat[i][j] = res.mat[i][j] + a.mat[i][k] * b.mat[k][j];
                res.mat[i][j] = res.mat[i][j] % mod;
            }
        }
    return res;
}
matrix pow_matrix(matrix a, ll n) {
    matrix res = unit_matrix;
    while (n != 0) {
        if (n & 1)
            res = mul(res, a);
        a = mul(a, a);
        n >>= 1;
    }
    return res;
}
int main() {
    ll n;
    while (~scanf("%lld",&n)) {
        if (n <= 2) {
            cout << "1" << endl;
            continue;
        }
        matrix tmp = {0, 1, 1, 1}, ans, x = {1, 1, 0, 0};
        ans = pow_matrix(tmp, n - 2);
        ans = mul(x, ans);
        cout << "    ";
        cout << ans.mat[0][1] << endl;
    }
    return 0;
}

以下是加强版嘻嘻嘻

#include <iostream>
#include <cstdio>
#define mod 1000000009
#define ll long long
using namespace std;
struct matrix {
    ll mat[2][2];
};
matrix unit_matrix = {1, 0, 0, 1}; //单位矩阵
matrix mul(matrix a, matrix b, int x, int y, int z) { //xy a的行列 yz b的行列
    matrix res;
    for (int i = 0; i < x; i++)
        for (int j = 0; j < z; j++) {
            res.mat[i][j] = 0;
            for (int k = 0; k < y; k++) {
                res.mat[i][j] = res.mat[i][j] + a.mat[i][k] * b.mat[k][j];
                res.mat[i][j] = res.mat[i][j] % mod;
            }
        }
    return res;
}
matrix pow_matrix(matrix a, ll n, int x) {
    matrix res = unit_matrix;
    while (n != 0) {
        if (n & 1)
            res = mul(res, a, x, x, x);
        a = mul(a, a, x, x, x);
        n >>= 1;
    }
    return res;
}
int main() {
    ll n;
    while (~scanf("%lld", &n)) {
        if (n <= 2) {
            cout << "1" << endl;
            continue;
        }
        matrix tmp = {0, 1, 1, 1}, ans, x = {1, 1};
        ans = pow_matrix(tmp, n - 2, 2);
        ans = mul(x, ans, 1, 2, 2);
        cout << ans.mat[0][1] << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值