結果

問題 No.28 末尾最適化
コンテスト
ユーザー zeta
提出日時 2026-02-09 20:33:36
言語 C++23
(gcc 15.2.0 + boost 1.89.0)
結果
WA  
実行時間 -
コード長 22,684 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 8,449 ms
コンパイル使用メモリ 304,892 KB
実行使用メモリ 7,972 KB
最終ジャッジ日時 2026-02-09 20:33:52
合計ジャッジ時間 6,769 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 1 WA * 1
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#line 1 "No_28_\u672b\u5c3e\u6700\u9069\u5316.cpp"
#define YRSD
#line 2 "YRS/all.hpp"

#line 2 "YRS/aa/head.hpp"

#include <iostream>
#include <algorithm>

#include <array>
#include <bitset>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <tuple>

#include <bit>
#include <chrono>
#include <functional>
#include <iomanip>
#include <utility>
#include <type_traits>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstring>
#include <ctime>
#include <limits>
#include <ranges>
#include <concepts>

#define TE template <typename T>
#define TES template <typename T, typename ...S>
#define Z auto
#define ep emplace_back
#define eb emplace
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()

#define OV4(a, b, c, d, e, ...) e
#define FOR1(a) for (int _ = 0; _ < (a); ++_)
#define FOR2(i, a) for (int i = 0; i < (a); ++i)
#define FOR3(i, a, b) for (int i = (a); i < (b); ++i)
#define FOR4(i, a, b, c) for (int i = (a); i < (b); i += (c))
#define FOR(...) OV4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR1_R(a) for (int _ = (a) - 1; _ >= 0; --_)
#define FOR2_R(i, a) for (int i = (a) - 1; i >= 0; --i)
#define FOR3_R(i, a, b) for (int i = (b) - 1; i >= (a); --i)
#define FOR4_R(i, a, b, c) for (int i = (b) - 1; i >= (a); i -= (c))
#define FOR_R(...) OV4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)
#define FOR_subset(t, s) for (int t = (s); t > -1; t = (t == 0 ? -1 : (t - 1) & s))

#define sort ranges::sort

using namespace std;

TE using vc = vector<T>;
TE using vvc = vc<vc<T>>;
TE using T1 = tuple<T>;
TE using T2 = tuple<T, T>;
TE using T3 = tuple<T, T, T>;
TE using T4 = tuple<T, T, T, T>;
TE using max_heap = priority_queue<T>;
TE using min_heap = priority_queue<T, vc<T>, greater<T>>;
using u8 = unsigned char; using uint = unsigned int; using ll = long long;      using ull = unsigned long long;
using ld = long double;   using i128 = __int128;     using u128 = __uint128_t;  using f128 = __float128;
using u16 = uint16_t;
using PII = pair<int, int>;   using PLL = pair<ll, ll>;

#ifdef YRSD
constexpr bool dbg = 1;
#else
constexpr bool dbg = 0;
#endif
#line 2 "YRS/IO/IO.hpp"

istream &operator>>(istream &I, i128 &x) {
  static string s;
  I >> s;
  int f = s[0] == '-';
  x = 0;
  const int N = (int)s.size();
  FOR(i, f, N) x = x * 10 + s[i] - '0';
  if (f) x = -x;
  return I;
}
ostream &operator<<(ostream &O, i128 x) {
  static string s;
  s.clear();
  bool f = x < 0;
  if (f) x = -x;
  while (x) s += '0' + x % 10, x /= 10;
  if (s.empty()) s += '0';
  if (f) s += '-';
  reverse(all(s));
  return O << s;
}
istream &operator>>(istream &I, f128 &x) {
  static string s;
  I >> s, x = stold(s);
  return I;
}
ostream &operator<<(ostream &O, const f128 x) { return O << ld(x); }
template <typename ...S> istream &operator>>(istream &I, tuple<S...> &t) {
  return apply([&I](Z &...args) { ((I >> args), ...); }, t), I;
}
template <typename T, typename U>
istream &operator>>(istream &I, pair<T, U> &x) {
  return I >> x.fi >> x.se;
}
template <typename T, typename U>
ostream &operator<<(ostream &O, const pair<T, U> &x) {
  return O << x.fi << ' ' << x.se;
}
template <typename T>
requires requires(T &c) { begin(c); end(c); } and 
                          (not is_same_v<decay_t<T>, string>)
istream &operator>>(istream &I, T &c) {
  for (Z &e : c) I >> e;
  return I;
}
template <typename T>requires requires(const T &c) { begin(c); end(c); } and 
  (not is_same_v<decay_t<T>, const char*>) and 
  (not is_same_v<decay_t<T>, string>) and 
  (not is_array_v<remove_reference_t<T>> or 
   not is_same_v<remove_extent_t<remove_reference_t<T>>, char>)
ostream &operator<<(ostream &O, const T &a) {
  if (a.empty()) return O;
  Z i = a.begin();
  O << *i++;
  for (; i != a.end(); ++i) O << ' ' << *i;
  return O;
}
void IN() {}
TE void IN(T &x, Z &...s) { cin >> x, IN(s...); }
void print() { cout << '\n'; }
TES void print(T &&x, S &&...y) {
  cout << x;
  if constexpr (sizeof...(S)) cout << ' ';
  print(forward<S>(y)...);
}
void put() { cout << ' '; }
TES void put(T &&x, S &&...y) {
  cout << x;
  if constexpr (sizeof...(S)) cout << ' ';
  put(forward<S>(y)...);
}

#define INT(...)  int    __VA_ARGS__; IN(__VA_ARGS__)
#define LL(...)   ll     __VA_ARGS__; IN(__VA_ARGS__)
#define ULL(...)  ull    __VA_ARGS__; IN(__VA_ARGS__)
#define I128(...) i128   __VA_ARGS__; IN(__VA_ARGS__)
#define STR(...)  string __VA_ARGS__; IN(__VA_ARGS__)
#define CH(...)   char   __VA_ARGS__; IN(__VA_ARGS__)
#define REAL(...) re     __VA_ARGS__; IN(__VA_ARGS__)
#define VEC(T, a, n) vc<T> a(n); IN(a)
#define VVEC(T, a, n, m) vvc<T> a(n, vc<T>(m)); IN(a)

void YES(bool o = 1) { print(o ? "YES" : "NO"); }
void Yes(bool o = 1) { print(o ? "Yes" : "No"); }
void yes(bool o = 1) { print(o ? "yes" : "no"); }
void NO(bool o = 1) { YES(not o); }
void No(bool o = 1) { Yes(not o); }
void no(bool o = 1) { yes(not o); }
void ALICE(bool o = 1) { print(o ? "ALICE" : "BOB"); }
void Alice(bool o = 1) { print(o ? "Alice" : "Bob"); }
void alice(bool o = 1) { print(o ? "alice" : "bob"); }
void BOB(bool o = 1) { ALICE(not o); }
void Bob(bool o = 1) { Alice(not o); }
void bob(bool o = 1) { alice(not o); }
void POSSIBLE(bool o = 1) { print(o ? "POSSIBLE" : "IMPOSSIBLE"); }
void Possible(bool o = 1) { print(o ? "Possible" : "Impossible"); }
void possible(bool o = 1) { print(o ? "possible" : "impossible"); }
void IMPOSSIBLE(bool o = 1) { POSSIBLE(not o); }
void Impossible(bool o = 1) { Possible(not o); }
void impossible(bool o = 1) { possible(not o); }
void TAK(bool o = 1) { print(o ? "TAK" : "NIE"); }
void NIE(bool o = 1) { TAK(not o); }
#line 5 "YRS/all.hpp"

#if (__cplusplus >= 202002L)
#include <numbers>
constexpr ld pi = numbers::pi;
#endif
TE constexpr T inf = numeric_limits<T>::max();
template <> constexpr i128 inf<i128> = i128(numeric_limits<ll>::max()) * 2'000'000'000'000'000'000;
template <typename T, typename U>
constexpr pair<T, U> inf<pair<T, U>> = {inf<T>, inf<U>};

TE constexpr static inline int pc(T x) { return popcount(make_unsigned_t<T>(x)); }
constexpr static inline ll len(const Z &a) { return a.size(); }

void reverse(Z &a) { reverse(all(a)); }

void unique(Z &a) {
  sort(a);
  a.erase(unique(all(a)), a.end());
}
TE vc<int> inverse(const vc<T> &a) {
  int N = len(a);
  vc<int> b(N, -1);
  FOR(i, N) if (a[i] != -1) b[a[i]] = i;
  return b;
}

Z QMAX(const Z &a) { return *max_element(all(a)); }
Z QMIN(const Z &a) { return *min_element(all(a)); }
constexpr bool chmax(Z &a, const Z &b) { return (a < b ? a = b, true : false); }
constexpr bool chmin(Z &a, const Z &b) { return (a > b ? a = b, true : false); }

template <typename T, typename U>
constexpr static pair<T, U> operator-(const pair<T, U> &p) {
  return pair<T, U>(-p.fi, -p.se);
}

vc<int> argsort(const Z &a) {
  vc<int> I(len(a));
  iota(all(I), 0);
  sort(I, [&](int i, int k) { return a[i] < a[k] or (a[i] == a[k] and i < k); });
  return I;
}
TE vc<T> rearrange(const vc<T> &a, const vc<int> &I) {
  int N = len(I);
  vc<T> b(N);
  FOR(i, N) b[i] = a[I[i]];
  return b;
}
template <int off = 1, typename T> 
vc<T> pre_sum(const vc<T> &a) {
  int N = len(a);
  vc<T> c(N + 1);
  FOR(i, N) c[i + 1] = c[i] + a[i];
  if constexpr (off == 0) c.erase(c.begin());
  return c;
}

TE constexpr static int topbit(T x) {
  if (x == 0) return - 1;
  if constexpr (sizeof(T) <= 4) return 31 - __builtin_clz(x);
  else return 63 - __builtin_clzll(x);
}
TE constexpr static int lowbit(T x) {
  if (x == 0) return -1;
  if constexpr (sizeof(T) <= 4) return __builtin_ctz(x);
  else return __builtin_ctzll(x);
}

TE constexpr T floor(T x, T y) { return x / y - (x % y and (x ^ y) < 0); }
TE constexpr T ceil(T x, T y) { return floor(x + y - 1, y); }
TE constexpr T bmod(T x, T y) { return x - floor(x, y) * x; }
TE constexpr pair<T, T> divmod(T x, T y) {
  T q = floor(x, y);
  return pair{q, x - q * y};
}
template <typename T = ll>
T SUM(const Z &v) {
  return accumulate(all(v), T(0));
}
int lb(const Z &a, Z x) { return lower_bound(all(a), x) - a.begin(); }
int ub(const Z &a, Z x) { return upper_bound(all(a), x) - a.begin(); }

template <bool ck = true>
ll bina(Z F, ll l, ll r) {
  if constexpr (ck) assert(F(l));
  while (abs(l - r) > 1) {
    ll x = (r + l) >> 1;
    (F(x) ? l : r) = x;
  }
  return l;
}
TE T bina_real(const Z &F, T l, T r, int c = 100) {
  while (c--) {
    T m = (l + r) / 2;
    (F(m) ? l : r) = m;
  }
  return (l + r) / 2;
}

Z pop(Z &s) {
  if constexpr (requires { s.pop_back(); }) {
    Z x = s.back();
    return s.pop_back(), x;
  } else if constexpr (requires { s.top(); }) {
    Z x = s.top();
    return s.pop(), x;
  } else {
    Z x = s.front();
    return s.pop(), x;
  }
}
void setp(int x) { cout << fixed << setprecision(x); }

TE inline void sh(vc<T> &a, int N) {
  a.resize(N, T(0));
}
#line 1 "YRS/debug.hpp"
#ifdef YRSD
void DBG() { cerr << "]" << endl; }
TES void DBG(T &&x, S &&...y) {
  cerr << x;
  if constexpr (sizeof...(S)) cerr << ", ";
  DBG(forward<S>(y)...);
}
#define debug(...) cerr << "[" << __LINE__ << "]: [" #__VA_ARGS__ "] = [", DBG(__VA_ARGS__)
void ERR() { cerr << endl; }
TES void ERR(T &&x, S &&...y) {
  cerr << x;
  if constexpr (sizeof...(S)) cerr << ", ";
  ERR(forward<S>(y)...);
}
#define err(...) cerr << "[" << __LINE__ << "]: ", ERR(__VA_ARGS__)
#define asser assert
#else
#define debug(...) void(0721)
#define err(...)   void(0721)
#define asser(...) void(0721)
#endif
#line 4 "No_28_\u672b\u5c3e\u6700\u9069\u5316.cpp"
// #include "YRS/IO/fast_io.hpp"
// #include "YRS/random/rng.hpp"
#line 2 "YRS/mod/modint.hpp"

#line 2 "YRS/mod/modint_common.hpp"

template <class T>
concept is_mint = requires(T x) {
  { T::get_mod() };
  { T::gen(0ull) } -> same_as<T>;
  x.val;
};
template <class mint>
concept has_const_mod =
    requires { integral_constant<int, (int)mint::get_mod()> {}; };

template <typename mint>
static vc<mint> &invs() {
  static vc<mint> a{0, 1};
  return a;
}
template <typename mint>
static vc<mint> &fac() {
  static vc<mint> a{1, 1};
  return a;
}
template <typename mint>
static vc<mint> &ifac() {
  static vc<mint> a{1, 1};
  return a;
}

template <typename mint>
static int Set_inv(int N) {
  static vc<mint> &inv = invs<mint>();
  if (len(inv) >= N) return N;
  inv.resize(N + 1);
  inv[0] = 1, inv[1] = 1;
  FOR(i, 1, N) inv[i + 1] = inv[i] * i;
  mint t = pop(inv).inv();
  FOR_R(i, N) inv[i] *= t, t *= i;
  return N;
}
template <typename mint>
static int Set_comb(int N) {
  static vector<mint> &fa = fac<mint>(), &ifa = ifac<mint>();
  if (len(fa) >= N) return N;
  fa.resize(N);
  ifa.resize(N);
  FOR(i, 1, N) fa[i] = fa[i - 1] * i;
  ifa[N - 1] = fa[N - 1].inv();
  FOR_R(i, N - 1) ifa[i] = ifa[i + 1] * (i + 1);
  return N;
}

template <typename mint>
mint inv(int n) {
  static const int mod = mint::get_mod();
  static vc<mint> &a = invs<mint>();
  assert(0 <= n);
  while (len(a) <= n) {
    int k = len(a);
    int q = (mod + k - 1) / k;
    int r = k * q - mod;
    a.ep(a[r] * mint(q));
  }
  return a[n];
}
template <typename mint>
mint fact(int n) {
  static const int mod = mint::get_mod();
  static vc<mint> &a = fac<mint>();
  assert(0 <= n);
  if (n >= mod) return 0;
  while (len(a) <= n) {
    int k = len(a);
    a.ep(a[k - 1] * mint(k));
  }
  return a[n];
}

template <typename mint>
mint fact_inv(int n) {
  static vc<mint> &a = ifac<mint>();
  if (n < 0) return mint(0);
  while (len(a) <= n)
    a.ep(a[len(a) - 1] * inv<mint>(len(a)));
  return a[n];
}

template <typename mint, typename... Ts>
mint fact_invs(Ts... xs) {
  return (mint(1) * ... * fact_inv<mint>(xs));
}

template <typename mint, typename Head, typename... Tail>
mint multinomial(Head&& head, Tail&&... tail) {
  return fact<mint>(head) * fact_invs<mint>(forward<Tail>(tail)...);
}

template <typename mint>
mint C_dense(int n, int k) {
  assert(n >= 0);
  if (k < 0 or n < k) return 0;
  static vc<vc<mint>> C;
  static int H = 0, W = 0;
  Z calc = [&](int i, int j) -> mint {
    if (i == 0) return(j == 0 ? mint(1) : mint(0));
    return C[i - 1][j] + (j ? C[i - 1][j - 1] : 0);
  };
  if (W <= k) {
    for (int i = 0; i < H; ++i) {
      C[i].resize(k + 1);
      for (int j = W; j < k + 1; ++j) {
        C[i][j] = calc(i, j);
      }
    }
    W = k + 1;
  }
  if (H <= n) {
    C.resize(n + 1);
    for (int i = H; i < n + 1; ++i) {
      C[i].resize(W);
      for (int j = 0; j < W; ++j) {
        C[i][j] = calc(i, j);
      }
    }
    H = n + 1;
  }
  return C[n][k];
}

template <typename mint>
mint C(int N, int K) {
  assert(N >= 0);
  if (K < 0 or N < K) return 0;
  return fact<mint>(N) * fact_inv<mint>(K) * fact_inv<mint>(N - K);
}

template <typename mint>
mint lucas(ll N, ll K) {
  static constexpr int P = mint::get_mod();
  if (K > N) return 0;
  if (K == 0) return 1;
  return C<mint>(N % P, K % P) * lucas<mint>(N / P, K / P);
}

template <typename mint, bool large = false, bool dense = false>
mint binom(ll n, ll k) {
  assert(n >= 0);
  if (k < 0 or n < k) return 0;
  if constexpr (dense) return C_dense<mint>(n, k);
  if constexpr (not large) return multinomial<mint>(n, k, n - k);
  k = min(k, n - k);
  mint x(1);
  FOR(i, k) x *= mint(n - i);
  return x * fact_inv<mint>(k);
}

template <typename mint, bool large = false>
mint C_inv(ll n, ll k) {
  assert(n >= 0);
  assert(0 <= k and k <= n);
  if (not large) return fact_inv<mint>(n) * fact<mint>(k) * fact<mint>(n - k);
  return mint(1) / binom<mint, 1>(n, k);
}

// [x^d](1-x)^{-n}
template <typename mint, bool large = false, bool dense = false>
mint C_negative(ll n, ll d) {
  assert(n >= 0);
  if (d < 0) return mint(0);
  if (n == 0) return (d == 0 ? mint(1) : mint(0));
  return binom<mint, large, dense>(n + d - 1, d);
}

#define CC C<mint>
#define fac fact<mint>
#define ifac fact_inv<mint>
#define set_comb Set_comb<mint>
#define set_inv Set_inv<mint>
#line 4 "YRS/mod/modint.hpp"

#define M modint
#define C constexpr
template <int mod>
struct M {
  static C uint m = mod;
  uint val;

  C M() : val(0) {}
  C M(uint x) : val(x % m) {}
  C M(ull x) : val(x % m) {}
  C M(u128 x) : val(x % m) {}
  C M(int x) : val((x %= mod) < 0 ? x + mod : x) {}
  C M(ll x) : val((x %= mod) < 0 ? x + mod : x) {}
  C M(i128 x) : val((x %= mod) < 0 ? x + mod : x) {}

  C M &operator+=(M p) {
    if ((val += p.val) >= m) val -= m;
    return *this;
  }
  C M &operator-=(M p) {
    if ((val += m - p.val) >= m) val -= m;
    return *this;
  }
  C M operator+(M p) const { return M(*this) += p; }
  C M operator-(M p) const { return M(*this) -= p; }

  C M &operator*=(M p) {
    val = ull(val) * p.val % m;
    return *this;
  }
  C M operator*(M p) const { return M(*this) *= p; }

  C M &operator/=(M p) { return *this *= p.inv(); }
  C M operator/(M p) const { return M(*this) /= p; }

  C M operator-() const { return M::gen(val ? mod - val : 0); }

  C M inv() const {
    int a = val, b = mod, x = 1, y = 0, t;
    while (b > 0) {
      t = a / b;
      swap(a -= t * b, b);
      swap(x -= t * y, y);
    }
    return M(x);
  }

  C M pow(ll k) const {
    if (k < 0) return inv().pow(-k);
    M s(1), a(val);
    for (; k; k >>= 1, a *= a)
      if (k & 1) s *= a;
    return s;
  }

  C bool operator<(M p) const { return val < p.val; }
  C bool operator==(M p) const { return val == p.val; }
  C bool operator!=(M p) const { return val != p.val; }

  static C M gen(uint x) {
    M s;
    s.val = x;
    return s;
  }

  friend istream &operator>>(istream &is, M &p) {
    ll x;
    is >> x;
    p = x;
    return is;
  }
  friend ostream &operator<<(ostream &os, M p) { return os << p.val; }

  static C int get_mod() { return mod; }

  static C PII ntt_info() {
    if (mod == 167772161) return {25, 17};
    if (mod == 469762049) return {26, 30};
    if (mod == 754974721) return {24, 362};
    if (mod == 998244353) return {23, 31};
    if (mod == 120586241) return {20, 74066978};
    if (mod == 880803841) return {23, 211};
    if (mod == 943718401) return {22, 663003469};
    if (mod == 1004535809) return {21, 582313106};
    if (mod == 1012924417) return {21, 368093570};
    return {-1, -1};
  }
  
  static C bool can_ntt() { return ntt_info().fi != -1; }
};
#undef M
#undef C

using M99 = modint<998244353>;
using M17 = modint<1000000007>;

#ifdef FIO
template <int mod>
void rd(modint<mod> &x) {
  LL(y);
  x = y;
}
template <int mod>
void wt(modint<mod> x) {
  wt(x.val);
}
#endif
#line 2 "YRS/pr/factors.hpp"

#line 2 "YRS/pr/prims_test.hpp"

struct MM {
  using uu = unsigned __int128;
  inline static ull m, r, nn;
  static void set_mod(ull m) {
    MM::m = m;
    nn = -uu(m) % m;
    r = m;
    FOR(5) r *= 2 - m * r;
    r = -r;
  }
  static ull reduce(uu x) {
    return (x + uu(ull(x) * r) * m) >> 64;
  }
  
  ull x;
  MM() : x(0) {}
  MM(ull x) : x(reduce(uu(x) * nn)) {}
  ull val() const {
    ull y = reduce(x);
    return y >= m ? y - m : y;
  }
  MM &operator+=(MM y) {
    x += y.x - (m << 1);
    x = (ll(x) < 0 ? x + (m << 1) : x);
    return *this;
  }
  MM &operator-=(MM y) {
    x -= y.x;
    x = (ll(x) < 0 ? x + (m << 1) : x);
    return *this;
  }
  MM &operator*=(MM y) {
    x = reduce(uu(x) * y.x);
    return *this;
  }
  MM operator+(MM y) const { return MM(*this) += y; }
  MM operator-(MM y) const { return MM(*this) -= y; }
  MM operator*(MM y) const { return MM(*this) *= y; }
  bool operator==(MM y) const {
    return (x >= m ? x - m : x) == (y.x >= m ? y.x - m : y.x);
  }
  bool operator!=(MM y) const { return not operator==(y); }
  MM pow(ull k) const {
    MM r = 1, a = *this;
    for (; k; k >>= 1, a *= a) if (k & 1) r *= a;
    return r;
  }
};

bool primetest(const ull x) {
  if (x == 2 or x == 3 or x == 5 or x == 7) return 1;
  if (x % 2 == 0 or x % 3 == 0 or x % 5 == 0 or x % 7 == 0) return 0;
  if (x < 121) return x > 1;
  const ull d = (x - 1) >> __builtin_ctzll(x - 1);
  MM::set_mod(x);
  const MM o(1), mo(x - 1);
  Z f = [&](ull a) -> bool {
    MM y = MM(a).pow(d);
    ull t = d;
    while (y != o and y != mo and t != x - 1) y *= y, t <<= 1;
    if (y != mo and t % 2 == 0) return 1;
    return 0;
  };
  if (x < (1ull << 32)) {
    for (ull a : {2, 7, 61}) if (f(a)) return 0;
  } else {
    for (ull a : {2, 325, 9'375, 281'78, 450'775, 978'050'4, 179'526'502'2}) {
      if (x <= a) return 1;
      if (f(a)) return 0;
    }
  }
  return 1;
}
ll rho(ll n, ll c) {
  MM::set_mod(n);
  const MM cc(c);
  Z f = [&](MM x) { return x * x + cc; };
  MM x = 1, y = 2, z = 1, q = 1;
  ll g = 1;
  const ll m = 1ll << (__lg(n) / 5);
  for (ll r = 1; g == 1; r <<= 1) {
    x = y;
    FOR(r) y = f(y);
    for (ll k = 0; k < r and g == 1; k += m) {
      z = y;
      FOR(i, min(m, r - k)) y = f(y), q *= x - y;
      g = gcd(q.val(), n);
    }
  }
  if (g == n) do {
    z = f(z);
    g = gcd((x - z).val(), n);
  } while (g == 1);
  return g;
}
#line 2 "YRS/random/rng.hpp"

#include <random>

#ifdef MeIoN
std::mt19937 rg(0);
std::mt19937_64 rd_64(0);
#else
std::mt19937 rg(std::chrono::steady_clock::now().time_since_epoch().count());
std::mt19937_64 rd_64(std::chrono::steady_clock::now().time_since_epoch().count());
#endif

uint rng() { return rg(); }
uint rng(uint lim) { return rg() % lim; }
int rng(int l, int r) { return l + rg() % (r - l); }
ull rng_64() { return rd_64(); }
ull rng_64(ull lim) { return rd_64() % lim; }
ll rng_64(ll l, ll r) { return l + rd_64() % (r - l); }

template <typename T>
void shuffle(vector<T> &v) {
  const int N = len(v);
  FOR(i, 1, N) {
    int k = rng(0, i + 1);
    if (i != k) swap(v[i], v[k]);
  }
}
#line 5 "YRS/pr/factors.hpp"

ll find_pr_e(ll x) {
  assert(x > 1);
  if (primetest(x)) return x;
  FOR(100) {
    ll e = rho(x, rng_64(x));
    if (primetest(e)) return e;
    x = e;
  }
  err("failed");
  assert(0);
  return -1;
}

vc<pair<ll, int>> factor(ll x) {
  assert(x >= 1);
  vc<pair<ll, int>> r;
  for (int e = 2; e < 100; ++e) {
    if (e * e > x) break;
    if (x % e == 0) {
      int c = 0;
      do {
        x /= e, c += 1;
      } while (x % e == 0);
      r.ep(e, c);
    }
  }
  while (x > 1) {
    ll e = find_pr_e(x);
    int c = 0;
    do {
      x /= e, c += 1;
    } while (x % e == 0);
    r.ep(e, c);
  }
  return sort(r), r;
}
vc<pair<ll, int>> factor_by_lpf(ll n, vc<int> &lpf) {
  vc<pair<ll, int>> s;
  while (n > 1) {
    int p = lpf[n], e = 0;
    while (n % p == 0) n /= p, ++e;
    s.ep(p, e);
  }
  return s;
}
#line 2 "YRS/pr/lpf_table.hpp"

#line 2 "YRS/pr/primtable.hpp"

// [0, lm]
inline vc<int> primtable(int lm) {
  ++lm;
  static constexpr int sz = 32768;
  static int N = 2;
  static vc<int> s{2}, vis(sz + 1);

  if (N < lm) {
    N = lm;
    s = {2}, vis.assign(sz + 1, 0);
    int R = lm / 2;
    s.reserve(int(lm / log(lm) * 1.1));
    vc<PII> cp;
    FOR(i, 3, sz + 1, 2) {
      if (not vis[i]) {
        cp.ep(i, 1ll * i * i / 2);
        FOR(j, 1ll * i * i, sz + 1, i << 1) vis[j] = 1;
      }
    }
    FOR(L, 1, R + 1, sz) {
      array<bool, sz> f{};
      for (Z &[p, id] : cp)
        for (int i = id; i < sz + L; id = (i += p)) f[i - L] = 1;
      FOR(i, min(sz, R - L)) if (not f[i]) s.ep((L + i) << 1 | 1);
    }
  }
  int k = lb(s, lm + 1);
  return {s.begin(), s.begin() + k};
}
// [0, N]
inline vc<int> sie(int N) { return primtable(N); }
#line 4 "YRS/pr/lpf_table.hpp"

// 最大质因子
vc<int> lpf_table(int LIM) {
  Z prim = primtable(LIM);
  vc<int> minp(LIM + 1, -1);
  FOR_R(i, len(prim)) {
    Z p = prim[i];
    FOR(k, 1, LIM / p + 1) minp[p * k] = p;
  }
  return minp;
}
#line 9 "No_28_\u672b\u5c3e\u6700\u9069\u5316.cpp"

#define tests 1
#define fl 0
#define DB 10
using mint = modint<1'000'000'09>;
Z lpf = lpf_table(100);
void Yorisou() {
  INT(s, N, K, B);
  vc<int> a(N);
  a[0] = s;
  FOR(i, 1, N) a[i] = (mint(a[i - 1]) * a[i - 1] + mint(a[i - 1]) * 12345 + 1).val;
  Z fa = factor_by_lpf(B, lpf);
  int sz = len(fa);
  Z f = [&](vc<int> f) -> int {
    vc<int> c(sz);
    for (int x : f) FOR(i, sz) {
      while (x % fa[i].fi == 0) ++c[i], x /= fa[i].fi;
    }
    int re = inf<int>;
    FOR(i, sz) chmin(re, c[i] / fa[i].se);
    return re;
  };
  Z fp = [&](int x, int e) {
    int s = 0;
    while (x % e == 0) ++s, x /= e;
    return s;
  };
  int ans = inf<int>;
  for (Z [e, p] : fa) {
    sort(a, [&](mint x, mint y) -> bool {
      return fp(x.val, e) < fp(y.val, e);
    });
    chmin(ans, f(vc<int>{begin(a), begin(a) + K}));
  }
  print(ans - 1);
}
#line 1 "YRS/aa/main.hpp"
int main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  int T = 1;
  if (fl) cerr.tie(0);
  if (tests and not fl) IN(T);
  for (int i = 0; i < T or fl; ++i) {
    Yorisou();
    if (fl and i % DB == 0) cerr << "Case: " << i << '\n';
  }
  return 0;
}
#line 46 "No_28_\u672b\u5c3e\u6700\u9069\u5316.cpp"
0