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;
	}
}


發佈了88 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章