Advertisement
pb_jiang

abc270G

Sep 26th, 2022
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <assert.h>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. #define dbg(...) logger(#__VA_ARGS__, __VA_ARGS__)
  5. template <typename... Args> void logger(string vars, Args &&... values)
  6. {
  7.     cerr << vars << " = ";
  8.     string delim = "";
  9.     (..., (cerr << delim << values, delim = ", "));
  10.     cerr << endl;
  11. }
  12.  
  13. template <class T> using mpq = priority_queue<T, vector<T>, greater<T>>;
  14. using ll = long long;
  15. using pii = pair<int, int>;
  16.  
  17. int t;
  18. int p, a, b, s, g;
  19.  
  20. ll fast_pow(ll base, ll x, ll p)
  21. {
  22.     ll ret = 1;
  23.     ll pow = base;
  24.     while (x) {
  25.         if (x & 0x01)
  26.             ret = ret * pow % p;
  27.         x = x / 2;
  28.         pow = pow * pow % p;
  29.     }
  30.     return ret;
  31. }
  32.  
  33. ll solve()
  34. {
  35.     // dbg(p, a, b, s, g);
  36.     if (s == g)
  37.         return 0;
  38.     if (a == 0)
  39.         return (b == g ? 1 : -1);
  40.     ll m = sqrt(p);
  41.     ll inv_a = fast_pow(a, p - 2, p);
  42.     // dbg(m, inv_a);
  43.     unordered_map<ll, ll> small_step;
  44.     ll c = ((p - inv_a * b % p) % p + p) % p;
  45.     ll rem = (inv_a * g % p + c) % p;
  46.     // dbg(rem);
  47.     // small_step[s] = 0;
  48.     small_step[g] = 0;
  49.     for (int i = 0; i <= m; ++i) {
  50.         small_step[rem] = i + 1;
  51.         if (small_step.count(s))
  52.             return small_step[s];
  53.         // dbg(small_step[rem], rem);
  54.         rem = (inv_a * rem % p + c) % p;
  55.     }
  56.  
  57.     c = 0;
  58.     ll aa = 1;
  59.     ll an = fast_pow(a, m, p);
  60.     for (int i = 0; i < m; ++i) {
  61.         c = (aa + c) % p;
  62.         aa = aa * a % p;
  63.     }
  64.     c = c * b % p;
  65.     rem = (an * s % p + c) % p;
  66.     // dbg(rem);
  67.  
  68.     unordered_map<ll, ll> giant_step;
  69.     for (int i = 0; i <= p / m; ++i) {
  70.         giant_step[rem] = i + 1;
  71.         // dbg(giant_step[rem], rem);
  72.         if (small_step.count(rem))
  73.             return m * (i + 1) + small_step[rem];
  74.         rem = (an * rem % p + c) % p;
  75.     }
  76.  
  77.     return -1;
  78. }
  79.  
  80. int main(int argc, char **argv)
  81. {
  82.     scanf("%d", &t);
  83.     while (t--) {
  84.         scanf("%d%d%d%d%d", &p, &a, &b, &s, &g);
  85.         ll res = solve();
  86.         printf("%lld\n", res);
  87.     }
  88.     return 0;
  89. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement