题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5667
Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1230 Accepted Submission(s): 395
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.
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 .
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
Source
题目大意:Lcomyn 是个很厉害的选手,除了喜欢写17kb+的代码题,偶尔还会写数学题.他找到了一个数列:
fn=⎩⎨⎧1,ab,abfn−1cfn−2,n=1n=2otherwise 他给了你几个数:n,a,b,c,你需要告诉他fn模p后的数值.解题思路:
观察递推式我们可以发现,所有的fi都是a的幂次,所以我们先只对指数进行处理,我们会得到一个递推公式
x
n
=b+x
n-1
*c+x
n-2
;
由于数据量很大,所以我们转换成两个矩阵的乘法问题。
A矩阵:b 0 b
B矩阵:c 1 0
1 0 0
1 0 1
A*B两个矩阵相乘就可以实现2我们得到的递推公式。这样指数就处理完成了,最后在直接求a的矩阵的最左上角C.a[0][0]次幂即为最终结果。
详见代码。
#include <iostream>
#include <cstdio>
using namespace std;
#define LL long long
LL n,a,b,c,p;
struct node
{
LL a[3][3];
} A,B;
node cheng(node A,node B)
{
node C= {0,0,0,0,0,0,0,0,0};
for (int i=0; i<3; i++) //A的行
{
for (int j=0; j<3; j++) //B的列
{
for (int k=0; k<3; k++)
C.a[i][j]=(C.a[i][j]+A.a[i][k]*B.a[k][j])%(p-1);
}
}
return C;
}
node pow(node B,LL t)//矩阵快速幂
{
node s= {1,0,0,0,1,0,0,0,1};
while (t)
{
if (t%2==1)
s=cheng(s,B);
B=cheng(B,B);
t/=2;
}
return s;
}
LL mul(node A,node B)//求最后结果的指数
{
LL anx=A.a[0][0]*B.a[0][0]+A.a[0][1]*B.a[1][0]+A.a[0][2]*B.a[2][0];
return anx;
}
LL pow1(LL a,LL anx)
{
LL s=1;
while (anx)
{
if (anx%2==1)
s=(s*a)%p;
a=(a*a)%p;
anx/=2;
}
return s;
}
int main()
{
int T;
LL anx,ans;//anx表示最终结果的指数,ans表示最终所求的结果
scanf("%d",&T);
while (T--)
{
cin>>n>>a>>b>>c>>p;
if (n==1)
{
printf ("1\n");
continue;
}
A.a[0][0]=b,A.a[0][1]=0,A.a[0][2]=b;//xn-1,xn-2,b
B.a[0][0]=c,B.a[0][1]=1,B.a[0][2]=0;
B.a[1][0]=1,B.a[1][1]=0,B.a[1][2]=0;
B.a[2][0]=1,B.a[2][1]=0,B.a[2][2]=1;
B=pow(B,n-2);
anx=mul(A,B);
ans=pow1(a,anx);
printf ("%lld\n",ans);
}
return 0;
}