Matrix fast power --HDU5667

Topic Link

Full analysis on paper, too lazy to write on the blog

I am a konjac, only the source code

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long LL;
const int maxn=107;
LL mod;
struct mat{
    LL m[maxn][maxn];
    int X, y; /// X is the row number and y is the number of columns 
} Unit;
 void init_unit () {
    memset(unit.m,0,sizeof(unit.m));
    for(int i=0;i<maxn;i++)
        unit.m[i][i]=1;
}
void show(mat a){
    for(int i=1;i<=a.x;i++){
        for(int j=1;j<=a.y;j++)
            printf("%d ",a.m[i][j]);
        printf("\n");
    }
}
food mat_mul (food A, food b) {
    mat c;
    c.x=a.x,c.y=b.y;
    memset(c.m,0,sizeof(c.m));
    for(int i=1;i<=c.x;i++)
    for(int j=1;j<=c.y;j++){
        for(int k=1;k<=a.y;k++){
            c.m[i][j]+=(a.m[i][k]*b.m[k][j])%(mod-1);
            c.m[i][j]%=mod-1;
        }
    }
    return c;
}
mat mat_QuickPow(mat a,LL b){
    matt years = unites;
    ans.x=a.x,ans.y=a.y;
    while(b){
        if(b&1)
            years = mat_mul (years,);
        a = mat_mul (a, a);
        b>>=1;
    }
    return years;
}
LL QuickPow(LL a,LL b){
    LL ans=1;
    while(b){
        if(b&1)ans=(ans*a)%mod;
        a=(a*a)%mod;
        b>>=1;
    }
    return years;
}
int t;
LL n,x,y,z;
int main () {
    scanf("%d",&t);
    init_unit();
    while(t--){
        scanf("%I64d%I64d%I64d%I64d%I64d",&n,&x,&y,&z,&mod);
        mat a;
        x = y = 3 ;
        a.m[1][1]=1,a.m[1][2]=y,a.m[1][3]=0;
        a.m[2][1]=0,a.m[2][2]=z,a.m[2][3]=1;
        a.m[3][1]=0,a.m[3][2]=1,a.m[3][3]=0;
        if(n==1){
            printf("1\n");
            continue;
        }
        if(n==2){
            printf("%I64d\n",QuickPow(x,y));
            continue;
        }
        a=mat_QuickPow(a,n-2);
        LL t=(a.m[1][2]+a.m[2][2]*y);
        printf("%I64d\n",QuickPow(x,t));
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/helman/p/11323639.html