HDU-5667-Sequence(矩阵快速幂+费马小定理)

32 篇文章 0 订阅

Sequence

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


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
 

Recommend
wange2014
 

Statistic |  Submit |  Discuss | Note


( a b) p[n]= a * ((a b) p[n-1]) c * ((a b) p[n-2]);递推式子可以这样写;
合并后变为(a b) p[n]=(a b) (c*p[n-1]+p[n-2]+1);
可以得到p[n]=c*p[n-1]+p[n-2]+1;
则可以构造矩阵

p[n]    c    1    1    p[n-1]
p[n-1]    =  1  0    0   *   p[n-2]
1       0   0    1      1

费马小定理 a(p-1)Ξ1%p   可以转化为ax%(p-1) =ax  %p


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#define INF 0x3f3f3f3f
using namespace std;
#define MAXN 10005
#define MAXM 50005
long long a,b,c,mod;
typedef struct
{
    long long m[3][3];
} Mat;
Mat A= {1,0,0,
        0,1,0,
        0,0,1,
       };

long long Num_quick_pow(long long a,long long n)
{
    long long ans=1;
    while(n)
    {
        if(n&1)ans=ans*a%mod;
        a=a*a%mod;
        n>>=1;
    }
    return ans;
}
Mat Mat_Mul(Mat a,Mat b)
{
    Mat ans;
    for(int i=0; i<3; ++i)
        for(int j=0; j<3; ++j)
        {
            ans.m[i][j]=0;
            for(int k=0; k<3; ++k)
                ans.m[i][j]=(ans.m[i][j]+a.m[i][k]*b.m[k][j]%(mod-1))%(mod-1);
        }
    return ans;
}
long long Mat_quick_pow(Mat P,long long n)
{
    Mat Ans=A;
    while(n)
    {
        if(n&1)Ans=Mat_Mul(Ans,P);
        P=Mat_Mul(P,P);
        n>>=1;
    }
    return (Ans.m[0][0]*b%(mod-1)+Ans.m[0][2]*b%(mod-1))%(mod-1);
}

int main()
{
    int T;
    long long n;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%I64d%I64d%I64d%I64d%I64d",&n,&a,&b,&c,&mod);
        if(n==1)
        {
            printf("1\n");
            continue;
        }
        if(n==2)
        {
            printf("%I64d\n",Num_quick_pow(a,b));
            continue;
        }
        Mat C= {c,1,1,
                1,0,0,
                0,0,1
               };
        if(a%mod==0)printf("0\n");
        else cout<<Num_quick_pow(a,Mat_quick_pow(C,n-2))<<endl;
    }
    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值