loj#2531. 「CQOI2018」破解 D-H 協議(BSGS)

自為風月馬前卒發表於2019-03-25

題意

題目連結

Sol

搞個BSGS板子出題人也是很棒棒哦

#include<bits/stdc++.h> 
#define Pair pair<int, int>
#define MP(x, y) make_pair(x, y)
#define fi first
#define se second
#define int long long 
#define LL long long 
#define ull unsigned long long 
#define Fin(x) {freopen(#x".in","r",stdin);}
#define Fout(x) {freopen(#x".out","w",stdout);}
using namespace std;
const int MAXN = 1e6 + 10, INF = 1e9 + 10;;
int mod;
const double eps = 1e-9;
template <typename A, typename B> inline bool chmin(A &a, B b){if(a > b) {a = b; return 1;} return 0;}
template <typename A, typename B> inline bool chmax(A &a, B b){if(a < b) {a = b; return 1;} return 0;}
template <typename A, typename B> inline LL add(A x, B y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
template <typename A, typename B> inline void add2(A &x, B y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
template <typename A, typename B> inline LL mul(A x, B y) {return 1ll * x * y % mod;}
template <typename A, typename B> inline void mul2(A &x, B y) {x = (1ll * x * y % mod + mod) % mod;}
template <typename A> inline void debug(A a){cout << a << '\n';}
template <typename A> inline LL sqr(A x){return 1ll * x * x;}
template <typename A, typename B> inline LL fp(A a, B p, int md = mod) {int b = 1;while(p) {if(p & 1) b = mul(b, a);a = mul(a, a); p >>= 1;}return b;}
template <typename A> A inv(A x) {return fp(x, mod - 2);}
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int G;
map<int, int> mp;
int solve(int x) {//g^ret = x (mod p)
    mp.clear(); int block = ceil(sqrt(mod)), base = fp(G, block);
    for(int i = 0, cur = x; i <= block; i++, mul2(cur, G)) mp[cur] = i;
    for(int i = 1, cur = base; i <= block; i++, mul2(cur, base)) if(mp[cur]) return i * block - mp[cur];    
    return 0;
}
/*
int solve(int x) {
    int now = 1;
    for(int i = 0; i<= mod; i++) {
        if(now == x) return i;
        mul2(now, G);
    }
    assert(1 == 2);
}
*/
signed main() {
    //freopen("a.in", "r", stdin);
    G = read(); mod = read();
    int N = read();
    while(N--) {
        int A = read(), B = read();
        cout << fp(G, solve(A) * solve(B)) << '\n';;
    }
    return 0;
}