您的位置:首页 > 其它

Bzoj3239:Discrete Logging:BSGS模板题

2016-04-11 20:57 441 查看
题目链接3239:Discrete Logging

裸BSGS,终于会写了QAQ

#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
const int maxn=1500010;
const int mod=99997;
LL p,b,c,ans;
bool flag;

struct hashmap{
int next[maxn],tot;
LL val[maxn];
int h[mod],As[maxn];
void push(LL x,int id){
int now=x%mod; if (now<0) now+=mod;
for (int i=h[now];i;i=next[i])
if (val[i]==x) return;
++tot; next[tot]=h[now]; h[now]=tot;
val[tot]=x; As[tot]=id; return;
}
int find(LL x){
int now=x%mod; if (now<0) now+=mod;
for (int i=h[now];i;i=next[i])
if (val[i]==x) return As[i];
return -1;
}
void init(){
memset(h,0,sizeof(h)); tot=0;
}
}s;

void exgcd(LL D,LL p,LL &x,LL &y){
LL t;
if(!p){x=1;y=0;return;}
exgcd(p,D%p,x,y);
t=x; x=y; y=t-D/p*y;
}

int main(){
while (~scanf("%lld%lld%lld",&p,&b,&c)){
s.init();
int m=ceil(sqrt(p));
LL last=1; s.push(1,0);
for (int i=1;i<m;++i){
LL x=(last*b%p+p)%p;
s.push(x,i); last=x;
}
LL x,y;
exgcd(1,p,x,y);
x=(x*c%p+p)%p;
if (s.find(x)!=-1)
{ans=0*m+s.find(x);printf("%lld\n",ans);continue;}
LL D=last*b%p,tmp=D;
flag=0;
for (int i=1;i<=m;++i){
exgcd(D,p,x,y);
x=(x*c%p+p)%p;
if (s.find(x)!=-1)
{ans=i*m+s.find(x);printf("%lld\n",ans);flag=1;break;}
D=(D*tmp%p+p)%p;
}
if (!flag) printf("no solution\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BZOJ OI BSGS