标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5667
1 5 3 3 3 233
190
f?n??=?????????1,?a?b??,?a?b??f?n?1?c??f?n?2??,???n=1?n=2?otherwise?? 他给了你几个数:n,a,b,c,你需要告诉他f?n??模p后的数值.解题思路:
#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;
}
标签:
原文地址:http://blog.csdn.net/qiqi_skystar/article/details/51264966