BZOJ5296 [CQOI2018] 破解D-H协议 【数学】【BSGS】

时间:2023-03-08 20:14:40

题目分析:

  裸题。

代码:

 

 #include<bits/stdc++.h>
using namespace std; typedef long long ll; const int BASE = ; #define mp make_pair ll g,p;
ll srt = ;
vector<pair<int,ll> > hash[]; ll fast_pow(ll now,ll pw){
if(pw == ) return now;
ll z = fast_pow(now,pw/);
z *= z ; z %= p;
if(pw & )z *= now,z %= p;
return z;
} void CreatHash(){
ll xm = fast_pow(g,srt);
ll hh = xm;
for(ll i=;(i-)*srt<=INT_MAX;i++,hh = (hh*xm)%p){
hash[hh % BASE].push_back(mp(i,hh));
}
} void read(){
scanf("%lld%lld",&g,&p);
CreatHash();
} ll solve(ll now){
ll hh = g;
for(int i=;i<=;i++,hh=(hh*g)%p){
ll nowp = (hh*now)%p;
for(int j=;j<hash[nowp%BASE].size();j++){
ll out = hash[nowp%BASE][j].second;
if(out == nowp){
out = hash[nowp%BASE][j].first;
return out*srt-i;
}
}
}
} void work(){
int n;scanf("%d",&n);
for(int i=;i<=n;i++){
ll a,b; scanf("%lld%lld",&a,&b);
ll hh = solve(a);
ll key = fast_pow(b,hh);
printf("%lld\n",key);
}
} int main(){
read();
work();
return ;
}