2019牛客多校第五场B-generator 1(矩阵快速幂)

本文介绍了一种使用十进制矩阵快速幂解决特定类型数学问题的方法,通常矩阵快速幂采用二进制,但此方法适用于需要十进制幂运算的场景。文章详细解释了解题思路,并提供了C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

generator 1

题目传送门

解题思路

矩阵快速幂。只是平时的矩阵快速幂是二进制的,这题要用十进制的快速幂。

代码如下

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;

inline int read(){
    int res = 0, w = 0; char ch = 0;
    while(!isdigit(ch)){
        w |= ch == '-', ch = getchar();
    }
    while(isdigit(ch)){
        res = (res << 3) + (res << 1) + (ch ^ 48);
        ch = getchar();
    }
    return w ? -res : res;
}

ll mod;
struct Matrix{
    ll m[2][2];
    Matrix(){
        m[0][0] = m[0][1] = m[1][0] = m[1][1] = 0;
    }
    Matrix operator*(const Matrix& a)const{
        Matrix ans;
        for(int i = 0; i < 2; i ++){
            for(int j = 0; j < 2; j ++)
                for(int k = 0; k < 2; k ++)
                    ans.m[i][j] = (ans.m[i][j] + m[i][k] * a.m[k][j]) % mod;
        }
        return ans;
    }
};

Matrix fpow(const Matrix& x, string str)
{
    int k = str.size() - 1;
    Matrix t = x;
    Matrix ans;
    ans.m[0][0] = 1, ans.m[1][1] = 1;
    while(k >= 0){
        for(int i = 1; i <= str[k] - '0'; i ++)
            ans = ans * t;
        Matrix temp = t * t;
        t = temp * temp;
        t = t * t * temp;
        --k;
    }
    return ans;
}

int main()
{
    ios::sync_with_stdio(false);
    ll x0, x1, a, b;
    string n;
    cin >> x0 >> x1 >> a >> b >> n >> mod;
    Matrix t;
    t.m[0][0] = a, t.m[0][1] = b, t.m[1][0] = 1;
    Matrix ans = fpow(t, n);
    printf("%lld\n", (ans.m[1][0] * x1 + ans.m[1][1] * x0) % mod);
    return 0;
}

转载于:https://www.cnblogs.com/whisperlzw/p/11289703.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值