hdu6172-(矩阵快速幂)

来源:互联网 发布:k均值聚类算法课件 编辑:程序博客网 时间:2024/06/03 23:27

题解:打表后你会找到规律an = 4an-1+17an-2-12an-3,然后套个矩阵快速幂就可以了


#include<iostream>#include<cstring>#include<algorithm>#include<cstdio>using namespace std;const int mod = 1e9+7;typedef long long int ll;struct mat{    ll a[3][3];};mat operator*(const mat &x,const mat &y){        mat z;        for(int i = 0; i < 3; i++)            for(int j = 0; j < 3; j++){                z.a[i][j] = 0;                for(int k = 0; k < 3; k++)                    z.a[i][j] = (z.a[i][j]+x.a[i][k]*y.a[k][j])%mod;            }        return z;}mat x = {1255,0,0,197,0,0,31,0,0};mat a = {4,17,-12,1,0,0,0,1,0};void calc(mat &ans,mat x,ll n){    while(n){        if(n&1)ans = x*ans;        x = x*x;        n/=2;    }}int main(){    int t;    ll n;    scanf("%d",&t);    while(t--){        scanf("%I64d",&n);        if(n<=4){            printf("%I64d\n",x.a[4-n][0]);            continue;        }        mat ans = x;        calc(ans,a,n-4);        printf("%I64d\n",(ans.a[0][0]%mod+mod)%mod);    }    return 0;}


原创粉丝点击