C - Reading comprehension 矩阵快速幂

  •  
  • C - Reading comprehension

  •  HDU - 4990 
  • 给出的f[n]与f[n-1]的关系还需要分奇偶讨论。为了列出矩阵找到前后递推关系找f[n],f[n-1]与f[n-1],f[n-2]的关系
  • 讨论一下奇偶发现无论奇偶都有一个固定的关系f[n]=f[n-1]+f[n-2]*2+1,直接列出递推矩阵即可
  • #include<bits/stdc++.h>
    using namespace std;
    #define maxn 5
    #define ll long long
    struct node
    {
        ll f[maxn][maxn];
    } A,B,C,D;
    int N,K,mod;
    node mul(node a,node b,int x,int y,int z)
    {
        node c;
        memset(c.f,0,sizeof(c.f));
        for(int i=0; i<x; i++)
            for(int j=0; j<y; j++)
                for(int k=0; k<z; k++)
                    c.f[i][j]=(c.f[i][j]+a.f[i][k]*b.f[k][j])%mod;
        return c;
    }
    node quickpow(node a,int b)
    {
        node ans;
        memset(ans.f,0,sizeof(ans.f));
        for(int i=0; i<3; i++)ans.f[i][i]=1;
        while(b)
        {
            if(b&1)ans=mul(ans,a,3,3,3);
            a=mul(a,a,3,3,3);
            b=b>>1;
        }
        return ans;
    }
    int main()
    {
        ll temp[maxn][maxn]= {{1,1,0},{2,0,0},{1,0,1}};
        memcpy(A.f,temp,sizeof(temp));
        B.f[0][0]=2;
        B.f[0][1]=B.f[0][2]=1;
        while(scanf("%d%d",&N,&mod)!=EOF)
        {
            if(N==1)
            {
                printf("%d\n",1%mod);
                continue;
            }
            C=quickpow(A,N-2);
            D=mul(B,C,1,3,3);
            printf("%lld\n",D.f[0][0]);
        }
        return 0;
    }
    
  •  
  •  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值