1. 程式人生 > >Discrete Logging POJ - 2417(BSGS)

Discrete Logging POJ - 2417(BSGS)

1.0 can origin hide ret isp namespace 技術分享 ons

Discrete Logging

POJ - 2417

題意:給P,B,N,求最小的L使得 BL≡N (mod P)

Baby Step Giant Step

技術分享
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <cmath>
 5 #define ll long long
 6 using namespace std;
 7 const int maxn=76543;
 8 int head[maxn],nex[maxn],hs[maxn],id[maxn];
9 int cnt; 10 void init(){ 11 memset(head,-1,sizeof(head)); 12 cnt=0; 13 } 14 void insert_(ll x,int i){ 15 int u=x%maxn; 16 hs[cnt]=x; 17 id[cnt]=i; 18 nex[cnt]=head[u]; 19 head[u]=cnt++; 20 } 21 int find_(ll x){ 22 int u=x%maxn; 23 for(int i=head[u];~i;i=nex[i]){ 24
if(hs[i]==x) return id[i]; 25 } 26 return -1; 27 } 28 29 ll a,b,c; 30 ll bsgs(ll a,ll b,ll c){ 31 if(b==1) return 0; 32 ll m=ceil(sqrt(c*1.0)); 33 ll x=1,p=1; 34 for(ll i=0;i<=m;i++){ 35 if(i==0) insert_(b%c,i); 36 else{ 37 p=p*a%c; 38 insert_(p*b%c,i);
39 } 40 } 41 ll ans=1,res=-1; 42 int u; 43 for(ll i=1;i<=m;i++){ 44 ans=ans*p%c; 45 if((u=find_(ans))!=-1){ 46 res=i*m-u; 47 break; 48 } 49 } 50 return res; 51 } 52 int main(){ 53 while(scanf("%lld%lld%lld",&c,&a,&b)!=EOF){ 54 init(); 55 ll ans=bsgs(a,b,c); 56 if(ans!=-1) printf("%lld\n",ans); 57 else puts("no solution"); 58 } 59 }
View Code

Discrete Logging POJ - 2417(BSGS)