hdu 5667 sequence



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
 
由递推式可知,fn是a的次幂,设gn=log a fn,则式子可写成gn=b+gn-1*c+gn-2;可用矩阵乘法
//
//|G(n)  |  |c 1 b|  |G(n-1)|
//|G(n-1)|= |1 0 0|* |G(n-2)|
//|1     |  |0 0 1|  |1     |
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
ll p;
struct node
{
	ll a[3][3];
};
node mul(node &a,node &b)
{
	node t;
	memset(t.a,0,sizeof(t.a));
	for(int i=0;i<3;i++)
	{
		for(int j=0;j<3;j++)
		{
			for(int k=0;k<3;k++)
			{
				t.a[i][j]+=(a.a[i][k]*b.a[k][j])%(p-1);
				t.a[i][j]%=(p-1); 
			}
		}
	}
	return t;
}
node pow(node a,ll n)
{
	node t;
	memset(t.a,0,sizeof(t.a));
	for(int i=0;i<3;i++)
	t.a[i][i]=1;
	while(n)
	{
		if(n&1)
		t=mul(t,a);
		a=mul(a,a);
		n=n/2;
	}
	return t;
}
ll fun(ll a,ll b,ll c)
{
	ll r=a%c,k=1;
	while(b)
	{
		if(b&1)
		k=(k*r)%c;
		r=(r*r)%c;
		b=b/2;
	}
	return k;
}
int main()
{
	ll t,n,a,b,c;
    cin>>t;
	while(t--)
	{
		cin>>n>>a>>b>>c>>p;
		if(n==1)
		{
			cout<<1<<endl;continue;
		}
		if(n==2)
		{
			cout<<fun(a,b,p)<<endl;continue;
		}
		node t;
		t.a[0][0]=c,t.a[0][1]=1,t.a[0][2]=b;
		t.a[1][0]=1,t.a[1][1]=0,t.a[1][2]=0;
		t.a[2][0]=0,t.a[2][1]=0,t.a[2][2]=1;
		node t1;
		t1=pow(t,n-2);
		ll ans=t1.a[0][0]*b+t1.a[0][2];
		ans=fun(a,ans,p);
		cout<<ans<<endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值