【矩阵快速幂】【C++】 Recursive sequence

题目链接:https://vjudge.net/problem/HDU-5950 ;

以下是本人题解,有问题的同学欢迎留言哦!

#include<iostream>
#include<cstdio>
using namespace std;
typedef long long in;
typedef in mat[7][7];
const int sz=7;
const in mod=2147493647LL;

void matmul(mat a,mat b,mat res){
    mat c={0};
    for(int i=0;i<sz;i++){
        for(int j=0;j<sz;j++){
            for(int k=0;k<sz;k++){
                c[i][j]=(c[i][j]+a[i][k]*b[k][j])%mod;
            }
        }
    }
    for(int i=0;i<sz;i++){
        for(int j=0;j<sz;j++){
            res[i][j]=c[i][j];
        }
    }
}
void matpow(mat a,in b,mat res){
    mat c={0};
    for(int i=0;i<sz;i++){
        c[i][i]=1;
    }
    while(b){
        if(b&1)matmul(c,a,c);
        matmul(a,a,a);
        b>>=1;
    }
    for(int i=0;i<sz;i++){
        for(int j=0;j<sz;j++){
            res[i][j]=c[i][j];
        }
    }
}

int main(){
    //freopen("in.txt","r",stdin);
    in a,b,n,t;
    scanf("%lld",&t);
    while(t--){
        scanf("%lld%lld%lld",&n,&a,&b);
        if(n==1){
            printf("%lld",a);
            continue;}
        mat e={
            {1,2,1,0,0,0,0},
            {1,0,0,0,0,0,0},
            {0,0,1,4,6,4,1},
            {0,0,0,1,3,3,1},
            {0,0,0,0,1,2,1},
            {0,0,0,0,0,1,1},
            {0,0,0,0,0,0,1}
        };
        matpow(e,n-2,e);
        in ans=0;
        in p[]={b,a,81,27,9,3,1};
        
        for(int i=0;i<7;i++){
            ans=(e[0][i]*p[i]%mod+ans)%mod;
        }
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/-9-QAQ-6-/p/11748412.html
今日推荐