HDU 4565 So Easy! (矩阵快速幂)

                                              So Easy!(题目链接)

思路:

AC Code:

#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<list>
#define mod 10000
#define Max 0x3f3f3f3f
#define Min 0xc0c0c0c0
#define mst(a) memset(a,0,sizeof(a))
#define f(i,a,b) for(int i=a;i<b;i++)
using namespace std;
typedef long long ll;
const int MAX_N = 1e3 + 5;
ll a, b, n, m;
struct Matirx{
    int r, c;
    ll mat[2][2];
};

Matirx m1, m2, m3;

Matirx Mul(Matirx a, Matirx b){
    Matirx c ;
    c.r = a.r, c.c = b.c;
    for(int i = 0; i < a.r; i++){
        for(int j = 0; j < b.c; j++){
            c.mat[i][j] = 0;
            for(int t = 0; t < a.c; t++){
                c.mat[i][j] += a.mat[i][t] * b.mat[t][j];
            }
            c.mat[i][j] %= m;
        }
    }
    return c;
}

Matirx quick_pow(int n){
    Matirx tmp = m2, res = m1;
    while(n){
        if(n & 1){
            res = Mul(res, tmp);
        }
        tmp = Mul(tmp, tmp);
        n >>= 1;
    }
    return res;
}
void init(){
    m1.c = 2, m1.r = 2, m2.c = 2, m2.r = 2, m3.r = 2, m3.c = 1;
    m1.mat[0][0] = 1, m1.mat[0][1] = 0, m1.mat[1][0] = 0, m1.mat[1][1] = 1;
    m2.mat[0][0] = 0, m2.mat[0][1] = 1, m2.mat[1][0] = b - a * a, m2.mat[1][1] = 2 * a;
    m3.mat[0][0] = 2 * a, m3.mat[1][0] = 2 * (a * a + b);
}
int main(){
    //freopen("c1.txt", "r", stdin);
    //freopen("c2.txt", "w", stdout);
    while(scanf("%I64d%I64d%I64d%I64d", &a, &b, &n, &m) != EOF){
        init();
        if(n == 1){
            cout<<(2 * a) % m<<endl;
        }
        else if(n == 2){
            cout<<(2 * ( a * a + b) ) % m<<endl;
        }
        else {
            Matirx res = quick_pow(n - 2);
            m3 = Mul(res, m3);
            cout<<(m3.mat[1][0] + m) % m<<endl;
        }
    }
    //fclose(stdin);
    //fclose(stdout);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值