[bzoj3122][BSGS]隨機數生成器
阿新 • • 發佈:2018-12-09
Description
Input
輸入含有多組資料,第一行一個正整數T,表示這個測試點內的資料組數。 接下來T行,每行有五個整數p,a,b,X1,t,表示一組資料。保證X1和t都是合法的頁碼。
注意:P一定為質數
Output
共T行,每行一個整數表示他最早讀到第t頁是哪一天。如果他永遠不會讀到第t頁,輸出-1。
Sample Input
3
7 1 1 3 3
7 2 2 2 0
7 2 2 2 1
Sample Output
1
3
-1
HINT
0<=a<=P-1,0<=b<=P-1,2<=P<=10^9\
題解
講個笑話 我居然連 等比數列 求和公式
其中a是公比 把柿子拆開 差不多是一個 把b提出來後面就是個等比數列..都不知道大言不慚扔一個上來因為不知道怎麼O(1)求卡了半個小時的我你敢信一通亂化簡後大概是這樣 移項就是BSGS模板了.. 然後 需要一些特判 a=0或者1的情況以及x1=0的情況..
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<map>
#define LL long long
using namespace std;
map<LL,int> q;
LL mod,a,b,x1,T;
LL pow_mod(LL a,LL b)
{
LL ret=1;
while(b)
{
if(b&1)ret=ret*a %mod;
a=a*a%mod;b>>=1;
}
return ret;
}
LL exgcd(LL a,LL b,LL &x,LL &y)
{
if(a==0)
{
x=0;y=1;
return b;
}
else
{
LL tx,ty;
LL d=exgcd(b%a,a,tx,ty);
x=ty-(b/a)*tx;
y=tx;
return d;
}
}
LL BSGS(int y,int z)
{
if(y==0&&z==0){return 1;}
if(y==0&&z!=0){return -1;}
q.clear();
LL k=ceil(sqrt(mod)),tmp=1,p=pow_mod(y,mod-2);
q[z]=k+1;
for(int i=1;i<k;i++)
{
tmp=(LL)tmp*p%mod;
LL t=(LL)tmp*z%mod;
if(q[t]==0)q[t]=i;
}
tmp=1;p=pow_mod(y,k);
for(int i=0;i<k;i++)
{
if(q[tmp])
{
if(q[tmp]==k+1)return i*k+1;
else return i*k+q[tmp]+1;
}
tmp=(LL)tmp*p%mod;
}
return -1;
}
int main()
{
// freopen("a.in","r",stdin);
// freopen("a.out","w",stdout);
int Q;scanf("%d",&Q);
while(Q--)
{
scanf("%lld%lld%lld%lld%lld",&mod,&a,&b,&x1,&T);
if(x1==0)
{
if(b==0)
{
if(T==0)puts("1");
else puts("-1");
continue;
}
}
if(a==0)
{
if(x1==T)puts("1");
else if(b==T)puts("2");
else puts("-1");
continue;
}
if(a==1)
{
LL A=b,B=mod,x,y,K=T-x1;
LL d=exgcd(A,B,x,y);
if(K%d){puts("-1");continue;}
x=(x*(K/d)%(B/d)+(B/d))%(B/d);
if(x-(B/d)>=0)x-=(B/d);
printf("%lld\n",x+1);continue;
}
T%=mod;
LL gg=-b;
gg=gg*pow_mod(a-1,mod-2)%mod;
x1=(x1-gg+mod)%mod;
T=(T-gg+mod)%mod;
T=T*pow_mod(x1,mod-2)%mod;
printf("%lld\n",BSGS(a,T));
}
return 0;
}