hdu 2604 Queuing 矩阵快速幂

来源:互联网 发布:c语言开发技术详解 编辑:程序博客网 时间:2024/05/09 08:23

推出矩阵的公式即可:

传送门: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;}


0 0
原创粉丝点击