您的位置:首页 > 产品设计 > UI/UE

hdu 5667 sequence

2016-04-17 13:10 316 查看
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,abfcn−1fn−2,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.

1≤T≤10,1≤n≤1018,1≤a,b,c≤109,p is
a prime number,and p≤109+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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: