bzoj5296 [Cqoi2018] Crack DH protocol [BSGS]

portal

Problem solving ideas:

BSGS template questions.

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int getint()
{
    int i=0,f=1;char c;
    for(c=getchar();(c!='-')&&(c<'0'||c>'9');c=getchar());
    if(c=='-')c=getchar(),f=-1;
    for(;c>='0'&&c<='9';c=getchar())i=(i<<3)+(i<<1)+c-'0';
    return i*f;
}

const int N=50005;
ll g,p,S,n,A,B,x;
map<ll,int>mp;
ll Pow(ll x,ll y)
{
    ll res=1;
    for(;y;y>>=1,x=x*x%p)
        if(y&1)res=res*x%p;
    return res;
}
void solve()
{
    A=getint(),B=getint();
    ll tmp=Pow(A,p-2),a;
    for(int i=1;i<=S+1;i++)
    {
        tmp=tmp*x%p;
        if(mp[tmp]){a=i*S-mp[tmp];break;}
    }
    B=Pow(B,a);
    cout<<B<<'\n';
}
int main()
{
    //freopen("crack.in","r",stdin);
    //freopen("crack.out","w",stdout);
    g=getint(),p=getint(),n=getint(),S=sqrt(p)+1,x=1;
    for(int i=1;i<=S;i++)x=x*g%p,mp[x]=i;
    while(n--)solve();
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326136209&siteId=291194637