hdu 2604 Queuing 矩阵快速幂

本文介绍了一种高效的矩阵快速幂求解算法,通过优化矩阵乘法和幂次运算,实现复杂度降低,特别适用于大规模数据处理场景。该算法利用递归和模运算特性,简化了矩阵操作过程,有效提升了计算效率。

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

推出矩阵的公式即可:

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2604

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

int len_Matrix;
int Mod;

struct Matrix{
    int M[15][15];
};

void Init_Matrix(Matrix * tmp){
    for(int i=0;i<len_Matrix;i++){
        for(int j=0;j<len_Matrix;j++){
            tmp -> M[i][j] = 0;
        }
    }
    tmp -> M[0][0] = 1;tmp -> M[0][2] = 1;tmp -> M[0][3] = 1;
    tmp -> M[1][0] = 1;tmp -> M[2][1] = 1;tmp -> M[3][2] = 1;
}

Matrix multiply(Matrix a1,Matrix a2){
    Matrix ans;
    for(int i=0;i<len_Matrix;i++){
        for(int j=0;j<len_Matrix;j++){
            ans.M[i][j] = 0;
            for(int k=0;k<len_Matrix;k++){
               ans.M[i][j] = (a1.M[i][k]*a2.M[k][j]+ans.M[i][j])%Mod; 
            }
        }
    }
    return ans;
}

Matrix Pow(Matrix tmp,int nl){
    Matrix ans ;
    for(int i=0;i<len_Matrix;i++){
        for(int j=0;j<len_Matrix;j++){
            if(i==j)ans.M[i][j] = 1;
            else ans.M[i][j] = 0;
        }
    }
    while(nl){
        if(nl&1){
            ans = multiply(ans,tmp);
        }
        tmp = multiply(tmp,tmp);
        nl /= 2;
    }
    return ans;
}

void Debug_Matrix(Matrix ans){
    for(int i=0;i<len_Matrix;i++){
        for(int j=0;j<len_Matrix;j++){
            printf("%d ",ans.M[i][j]);
        }
        puts("");
    }
}

void Solve(int k,Matrix tmp){
    int tempa[4] ={2,4,6,9};
    if(k<=4)
        printf("%d\n",tempa[k-1]%Mod);
    else{
        Matrix ans = Pow(tmp,k-4);
        //Debug_Matrix(ans);
        int zans =0;
        for(int i=0;i<len_Matrix;i++){
            zans = (zans + ans.M[0][i] * tempa[3-i]) % Mod;
        }
        printf("%d\n",zans);
    }
}

void Input(){
    int k,m;
    while(~scanf("%d %d",&k,&m)){
        Matrix tmp;
        Init_Matrix(&tmp);
        //Debug_Matrix(tmp);
        Mod = m;
        len_Matrix = 4;
        Solve(k,tmp);
    }
}

void File(){
    freopen("a.in","r",stdin);
    freopen("a.out","w",stdout);
}

int main(void){
    //File();
    Input();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值