hdu 5667(矩阵快速幂+欧拉函数)

Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1405    Accepted Submission(s): 461


Problem Description
     Holion August will eat every thing he has found.

     Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.

fn=1,ab,abfcn1fn2,n=1n=2otherwise

     He gives you 5 numbers n,a,b,c,p,and he will eat  fn  foods.But there are only p foods,so you should tell him  fn  mod p.
 

Input
     The first line has a number,T,means testcase.

     Each testcase has 5 numbers,including n,a,b,c,p in a line.

    1T10,1n1018,1a,b,c109 , p  is a prime number,and  p109+7 .
 

Output
     Output one number for each case,which is  fn  mod p.
 

Sample Input
  
  
1 5 3 3 3 233
 

Sample Output
  
  
190
 

Source


对式子两边取对数 化简后会变成相加的递推式  在化成矩阵  由于矩阵是在指数上 所以需要模欧拉函数 又因为是质数 即p-1
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll n,a,b,c,Mod;

struct Matrix
{
    ll ma[3][3];
    void init()
    {
        memset(ma,0,sizeof(ma));
        ma[0][1]=ma[1][0]=ma[2][1]=ma[2][2]=1;
    }
}p;

Matrix Multi(Matrix a,Matrix b)
{
    Matrix res;
    memset(res.ma,0,sizeof(res.ma));
    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            for(int k=0;k<3;k++)
                res.ma[i][j]=(res.ma[i][j]+a.ma[i][k]*b.ma[k][j]%Mod)%Mod;
    return res;
}

Matrix quick_pow(Matrix p,ll k)
{
    Matrix res;
    memset(res.ma,0,sizeof(res.ma));
    for(int i=0;i<3;i++)
        res.ma[i][i]=1;
    while(k)
    {
        if(k&1)
            res=Multi(res,p);
        k>>=1;
        p=Multi(p,p);
    }
    return res;
}
ll quick_pow(ll p,ll k)
{
    ll res=1;
    while(k)
    {
        if(k&1)
            res=res*p%Mod;
        k>>=1;
        p=(p*p)%Mod;;
    }
    return res;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        p.init();
        scanf("%lld%lld%lld%lld%lld",&n,&a,&b,&c,&Mod);
        if(n==2)
        {
            printf("%lld\n",quick_pow(a,b));
            continue;
        }
        else if(a%Mod==0)
        {
            puts("0");
            continue;
        }
        Mod--;
        p.ma[1][1]=c;
        Matrix res;
        memset(res.ma,0,sizeof(res.ma));
        res=quick_pow(p,n-1);
        ll ans=0;
        ans=(b*res.ma[1][0]%Mod+b*res.ma[2][0]%Mod)%Mod;
        Mod++;
        printf("%lld\n",quick_pow(a,ans));
    }
    return 0;
}


 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值