# Bzoj 3122 [Sdoi2013]随机数生成器(BSGS+exgcd)

Input

Output

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

/*

*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<map>
#define LL long long
#define MAXN 101
using namespace std;
LL T,p[MAXN],a[MAXN],b[MAXN],x1[MAXN],t[MAXN];
map<LL,int>s;
bool vis[MAXN];
bool flag1=true,flag2=true,flag3=true;
{
LL x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
return x*f;
}
void slove1(int i)
{
LL tot,sum;
tot=x1[i],sum=1;
while(true)
{
if(tot==t[i]) {printf("%d\n",sum);break;}
if(!vis[tot]) vis[tot]=true;
else {printf("-1\n");break;}
tot=(a[i]*tot+b[i])%p[i];
sum++;
}
for(int j=0;j<p[i];j++) vis[j]=0;
}
void exgcd(LL a1,LL b1,LL &x,LL &y)
{
if(!b1){x=1;y=0;return ;}
exgcd(b1,a1%b1,y,x),y-=(a1/b1)*x;
return ;
}
void slove2(int i)
{
if(!a[i])
{
if(b[i]==t[i]) printf("2\n");
else printf("-1\n");
return ;
}
LL c,g,tot,x,y;
c=(t[i]-x1[i]+p[i])%p[i];
if(!c){cout<<1<<endl;return;}
g=__gcd(b[i],p[i]);
if(c%g) {cout<<-1<<endl;return ;}
exgcd(b[i],p[i],x,y);
x=(x*c/g)%p[i];x++;
x=(x+p[i])%p[i];
cout<<x<<endl;
}
LL mi(LL a1,LL b1,LL p1)
{
LL tot1=1;//a1%=p1;
while(b1)
{
if(b1&1) tot1=tot1*a1%p1;
a1=a1*a1%p1;
b1>>=1;
}
}
void slove3(int i)
{
LL c,g,y;bool flag;
s.clear();flag=false;
c=mi(a[i]-1,p[i]-2,p[i]);
exgcd((b[i]*c+x1[i])%p[i],p[i],g,y);
if(g<p[i]) g=g%p[i]+p[i];
if(a[i]==1)
{
cout<<g+1<<endl;return ;
}
LL tmp1=(b[i]*c+t[i])%p[i],tmp2=__gcd(b[i]*c+x1[i],p[i]);
if(tmp1%tmp2) {cout<<-1<<endl;return ;}
g=((g*(tmp1/tmp2)+p[i])%p[i]+p[i])%p[i];
LL m=ceil(sqrt(p[i])),tot=1,tt;
for(int j=1;j<=m-1;j++)
{
tot=tot*a[i]%p[i];
if(!s[tot]) s[tot]=j;
}
tot=1;tmp1=mi(a[i],p[i]-m-1,p[i]);s[1]=m+1;
for(int k=0;k<=m-1;k++)
{
tt=s[tot*g%p[i]];
if(tt)
{
if(tt==m+1) tt=0;
flag=true;
cout<<k*m+tt+1<<endl;
break;
}
tot=tot*tmp1%p[i];
}
if(!flag) cout<<-1<<endl;
}
int main()
{
for(int i=1;i<=T;i++)
{
if(x1[i]==t[i]) {printf("1\n");continue;}
if(p[i]<=200) slove1(i);
else if(a[i]<2) slove2(i);
else slove3(i);
}
return 0;
}
posted @ 2017-02-24 17:27  nancheng58  阅读(115)  评论(0编辑  收藏  举报