HDU - 4565 So Easy! 矩阵快速幂

题目大意:求这里写图片描述

解题思路:这题跟HDU - 2256 Problem of Precision类似,只不过这题是向上取整
有一个隐藏的条件:(a-1)^2 < b < a ^ 2
表明a - 1 < b < a
也就是(a - sqrt(b) )^n是小于1的
附上HDU - 2256 Problem of Precision的题解链接http://blog.csdn.net/l123012013048/article/details/45847097
注意int的范围,有可能会溢出

#include<cstdio>
typedef long long ll;
const int N = 2;
struct Matrix{
    ll mat[N][N];
}A, B, tmp;
int a, b, n, m;

void init() {
    B.mat[0][0] = B.mat[1][1] = 1;
    B.mat[0][1] = B.mat[1][0] = 0;

    A.mat[0][0] = A.mat[1][1] = a;
    A.mat[0][1] = b;
    A.mat[1][0] = 1;
}

Matrix matrixMul(Matrix x, Matrix y) {
    for(int i = 0; i < N; i++)
        for(int j = 0; j < N; j++) {
            tmp.mat[i][j] = 0;
            for(int k = 0; k < N; k++)
                tmp.mat[i][j] += (x.mat[i][k] * y.mat[k][j]) % m;
        }
    return tmp;
}

void solve(){
    while(n) {
        if(n & 1)
            B = matrixMul(B,A);
        A = matrixMul(A,A);
        n >>= 1;
    }
}

int main() {
    while(scanf("%d%d%d%d", &a, &b, &n, &m) != EOF) {
        init();
        solve();
        printf("%I64d\n", (2 * B.mat[0][0]) % m);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值