hdu 2256 4565 矩阵快速幂

 矩阵快速幂专题+题解: 点击打开链接

hdu 4565 代码:

#include<stdio.h>
#include<iostream>
using namespace std;
#define ll long long
ll mod;
struct Ju
{
    ll x[4][4];
};
Ju operator *(const Ju& a,const Ju& b)
{
   Ju c;
   for(int i=0;i<2;i++)
   {
       for(int j=0;j<2;j++)
       {
           c.x[i][j]=0;
           for(int k=0;k<2;k++)
           {
               c.x[i][j]+=(a.x[i][k]*b.x[k][j])%mod;
               c.x[i][j]%=mod;

           }
       }
   }
   return c;
}
Ju pow(Ju a,ll n)
{
    Ju one;
    one.x[0][0]=one.x[1][1]=1;
    one.x[0][1]=one.x[1][0]=0;
    while(n)
    {
        if(n&1)
        {
            one=one*a;
        }
        a=a*a;
        n/=2;
    }

    return one;
}
int main()
{
    ll a,b,n,m;
    while(~scanf("%lld%lld%lld%lld",&a,&b,&n,&m))
    {
        mod=m;
        Ju A;
        A.x[0][0]=a;
        A.x[0][1]=b;
        A.x[1][0]=1;
        A.x[1][1]=a;
        Ju ans=pow(A,n-1);
        ll he=0;
        he+=(ans.x[0][0]*a)%mod;
        he+=ans.x[0][1]%mod;

        printf("%lld\n",(2*he)%mod);
    }
}
hdu 2256 代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int mod=1024;
struct Ju
{
    int x[4][4];
};
Ju operator *(Ju a,Ju b)
{
    Ju c;
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        {
            c.x[i][j]=0;
            for(int k=0;k<2;k++)
            {
                c.x[i][j]+=(a.x[i][k]*b.x[k][j])%mod;;
                c.x[i][j]%=mod;
            }
        }
    }
    return c;
}
Ju pow(Ju a,int n)
{
    Ju one;
    for(int i=0; i<2; i++)
    {
        for(int j=0; j<2; j++)
        {
            if(i==j)
                one.x[i][j]=1;
            else
                one.x[i][j]=0;
        }
    }
    while(n)
    {
        if(n&1)
        {
            one=one*a;
        }
        a=a*a;
        n/=2;
    }
    return one;
}
int main()
{
    int t;
    while(~scanf("%d",&t))
    {
        int n;
        while(t--)
        {
            Ju a;
            a.x[0][0]=5;
            a.x[0][1]=12;
            a.x[1][0]=2;
            a.x[1][1]=5;
            scanf("%d",&n);
            Ju ans=pow(a,n);
            printf("%d\n",(ans.x[0][0]*2-1)%mod);


        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值