矩阵快速幂

来源:互联网 发布:分区软件找不到硬盘 编辑:程序博客网 时间:2024/06/18 14:43

题目链接

矩阵的模板写起来还是比较熟悉的
要注意H最大只能开到100*100,再大就会炸掉(编译都不行)
三重循环一定要写好了

曲神今天给我辟了一下谣
矩阵计算的是每个数的系数,所以我们在计算最后答案的时候,第一列的所有元素都要算进去

//这里写代码片#include<cstdio>#include<cstring>#include<iostream>#define ll long long using namespace std;const ll mod=1000000007;struct node{    ll H[5][5];    node operator * (const node &a)const    {        node ans;        for (int i=1;i<=3;i++)            for (int j=1;j<=3;j++)            {                ans.H[i][j]=0;                for (int k=1;k<=3;k++)                    ans.H[i][j]=(ans.H[i][j]+H[i][k]*a.H[k][j])%mod;            }        return ans;    }    void clear()    {        memset(H,0,sizeof(H));    }    node KSM(int b)    {        b--;        node ans=(* this);        node a=(* this);        while (b)        {            if (b&1)                ans=ans*a;            b>>=1;            a=a*a;        }        return ans;    }};node H,A;int main(){    int n;    int T;    H.clear();     H.H[1][1]=1; H.H[1][2]=1; H.H[2][3]=1; H.H[3][1]=1;    scanf("%d",&T);    while (T--)    {        scanf("%d",&n);        if (n==1||n==2||n==3) {            printf("1\n");            continue;        }        A.clear();        A=H.KSM(n-3);        ll an=A.H[1][1]+A.H[2][1]+A.H[3][1];    //        an%=mod;        printf("%lld\n",an);    }    return 0;} 
原创粉丝点击