题目链接: http://www.lydsy.com/JudgeOnline/problem.php?id=3122
感谢my的题解:http://blog.csdn.net/xaphoenix/article/details/50719539
大致题意是:给你个方程,Xn+1=(aXn+b)%P,求最小的n满足Xn=t ,P是质数。
我们将递推式展开得到: Xn+1=a^n*x1+b+a^2*b+···+a^(n-1)*b。后半部分我们用等比数列进行化简。我们设d=(b/(a-1))%P。那么Xn+1=a^n*x1+d*a^n-db。令(x1+d)为p,x1+bd为q。那么q=p*a^n。令x=q/p。则a^n=x(mod P) 到这里后我们利用BSGS进行计算即可。注意本题的细节部分:x1==t,a==0,a==1。
注意要用LL ,一开始我自己的BSGS模板过样例的时候发现少1,,,纠结了一会 那么加一再交吧!就ok。
/**************************************************************
Problem: 3122
User: yukun133
Language: C++
Result: Accepted
Time:1832 ms
Memory:10684 kb
****************************************************************/
#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
#include<cmath>
#include<map>
using namespace std;
#define LL long long
const int N = 100100;
const int M = 1000100;
LL sz,num[N],pre[N],last[M];
LL quickpow(LL a,LL b,LL p){
LL res=1;a%=p;
while(b>0){
if(b & 1) res=(long long)res*a%p;
b>>=1;
a=(long long)a*a%p;
}
return res;
}
void Hash(LL x,LL y){
sz++;num[sz]=y;pre[sz]=last[x];last[x]=sz;
}
LL BSGS(LL y,LL z,LL p){ //return -1表示无解
memset(last,0,sizeof(last));
sz=0;z%=p;
if(z==1) return 0;
if(y%p==0){
if(z==0) return 1;
else return -1;
}
LL i,j,mi,limt=sqrt(p),now=z;
for(i=1;i<=limt+1;i++){
Hash(now%M,now);
now=(long long)now*y%p;
}
now=1;mi=quickpow(y,limt,p);
for(i=1;i<=limt+1;i++){
now=(long long)now*mi%p;
for(j=last[now%M];j;j=pre[j]){
if(num[j]==now){
return i*limt-j+1;
}
}
}
return -1;
}
void extendgcd(LL a,LL b,LL &d,LL &x,LL &y)
{
if(b==0){d=a;x=1;y=0;return;}
extendgcd(b,a%b,d,y,x);
y-=x*(a/b);
}
LL GetNi(LL A,LL M)
{
LL rex=0,rey=0;
LL td=0;
extendgcd(A,M,td,rex,rey);
return (rex%M+M)%M;
}
int main()
{
int T;
cin>>T;
LL p,a,b,x1,t;
while (T--)
{
cin>>p>>a>>b>>x1>>t;
if (t==x1)
{
printf("1\n");
continue;
}
if (a==0)
{
if (b==t) cout<<2<<endl;
else cout<<-1<<endl;
continue;
}
if (a==1)
{
t=(t+p-x1+b)%p;
t=(t*GetNi(b,p))%p;
if (t>0) printf("%d\n",t);
else if(b==0) printf("-1\n");
else printf("%d\n",p);
continue;
}
LL d=(b*GetNi(a-1,p))%p;
t=(t+d)%p;
x1=(x1+d)%p;
t=(t*GetNi(x1,p))%p;
LL ans=BSGS(a,t,p);
if(~ans)
cout<<ans+1<<endl;
else cout<<-1<<endl;
}
return 0;
}
/*
3
7 1 1 3 3
7 2 2 2 0
7 2 2 2 1
*/