洛谷传送门
BZOJ传送门
解析:
B S G S BSGS BSGS裸题啊,这里 g g g的若干次幂显然能够构造出 p p p除 0 0 0以外的剩余系。
那么我们直接维护所有 g k ⌈ p ⌉ g^{k\lceil\sqrt{p}\rceil} gk⌈p⌉余数对应的指数,存到 H a s h Hash Hash表里面,我偷懒用了unoedered_map,但是最好在能够保证自己考场 H a s h Hash Hash表不会写错的情况下再写这个,不然就把这道题当成 H a s h Hash Hash表练手题吧。
然后每次用 1 ≤ i ≤ ⌈ p ⌉ , g i 1\leq i\leq\lceil\sqrt{p}\rceil,g^i 1≤i≤⌈p⌉,gi来寻找需要的指数就行了。
代码:
#include<bits/stdc++.h>
#include<tr1/unordered_map>
using namespace std;
#define ll long long
#define re register
#define gc getchar
#define pc putchar
#define cs const
inline int getint(){
re int num;
re char c;
while(!isdigit(c=gc()));num=c^48;
while(isdigit(c=gc()))num=(num<<1)+(num<<3)+(c^48);
return num;
}
inline void outint(int a){
static char ch[23];
if(a==0)pc('0');
while(a)ch[++ch[0]]=a-a/10*10,a/=10;
while(ch[0])pc(ch[ch[0]--]^48);
}
int g,mod,step;
inline int quickpow(int a,int b,int res=1){
for(;b;b>>=1,a=1ll*a*a%mod)if(b&1)res=1ll*res*a%mod;
return res;
}
tr1::unordered_map<int,int> ma;
inline void init(){
step=ceil(sqrt(mod));
int now=quickpow(g,step),base=now;
for(int re i=2;i<=step;++i){
now=1ll*base*now%mod;
ma[now]=i*step;
}
}
inline int BSGS(ll a){
int now=1;
for(int re j=0;j<=step;++j){
if(ma.find(1ll*now*a%mod)!=ma.end())return ma[1ll*now*a%mod]-j;
now=1ll*now*g%mod;
}
}
int n;
signed main(){
g=getint();
mod=getint();
init();
n=getint();
while(n--){
int A=getint(),B=getint();
outint(quickpow(A,BSGS(B)));pc('\n');
}
return 0;
}