#define SINGLE_TESTCASE // #define MULTI_TESTCASE // #define AOJ_TESTCASE #define FAST_IO // #define FAST_CIO // #define INTERACTIVE #define INF 4'000'000'000'000'000'037LL #define EPS 1e-11 // https://github.com/miscalculation53/library/tree/wip/template/template_all.hpp // https://github.com/miscalculation53/library/tree/wip/template/template_all_but_modint.hpp // https://github.com/miscalculation53/library/tree/wip/template/template_types.hpp #include using namespace std; using ll = long long; using uint = unsigned int; using ull = unsigned long long; using pll = pair; using tlll = tuple; #define vc vector template using vvc = vc>; using vl = vc; using vstr = vc; using i128 = __int128_t; using u128 = __uint128_t; i128 stoi128(const string &s) { const bool neg = s.front() == '-'; u128 res = 0; for (int i = neg; i < (int)s.size(); i++) res = 10 * res + s[i] - '0'; if (neg) return -i128(res - 1) - 1; return i128(res); } string i128tos(i128 x) { if (x == 0) return "0"; string sign = "", res = ""; u128 ux; if (x < 0) ux = u128(-(x + 1)) + 1, sign = "-"; else ux = x; while (ux > 0) { res += '0' + ux % 10; ux /= 10; } reverse(res.begin(), res.end()); return sign + res; } istream &operator>>(istream &is, i128 &a) { string s; is >> s; a = stoi128(s); return is; } ostream &operator<<(ostream &os, const i128 &a) { os << i128tos(a); return os; } #define cauto const auto // https://github.com/miscalculation53/library/tree/wip/template/template_rep.hpp #define overload4(_1,_2,_3,_4,name,...) name #define rep1(i,n) for (ll i = 0, nnnnn = ll(n); i < nnnnn; i++) #define rep2(i,l,r) for (ll i = ll(l), rrrrr = ll(r); i < rrrrr; i++) #define rep3(i,l,r,d) for (ll i = ll(l), rrrrr = ll(r), ddddd = ll(d); ddddd > 0 ? i < rrrrr : i > rrrrr; i += d) #define rep(...) overload4(__VA_ARGS__, rep3, rep2, rep1)(__VA_ARGS__) #define repi1(i,n) for (int i = 0, nnnnn = int(n); i < nnnnn; i++) #define repi2(i,l,r) for (int i = int(l), rrrrr = int(r); i < rrrrr; i++) #define repi3(i,l,r,d) for (int i = int(l), rrrrr = int(r), ddddd = int(d); ddddd > 0 ? i < rrrrr : i > rrrrr; i += d) #define repi(...) overload4(__VA_ARGS__, repi3, repi2, repi1)(__VA_ARGS__) #define fe(...) for (auto __VA_ARGS__) #define fec(...) for (cauto &__VA_ARGS__) #define fem(...) for (auto &__VA_ARGS__) // https://github.com/miscalculation53/library/tree/wip/template/template_math.hpp // https://github.com/miscalculation53/library/tree/wip/utils/is_integral_ext.hpp template constexpr bool is_integral_ext = is_integral_v || is_same_v || is_same_v; template constexpr bool is_signed_ext = is_signed_v || is_same_v; template constexpr bool is_unsigned_ext = is_unsigned_v || is_same_v; // https://github.com/miscalculation53/library/tree/wip/utils/default_infty.hpp namespace default_infty_detail { template inline constexpr bool unsupported = false; } template inline bool chmax(T &a, U b) { return a < b ? a = b, true : false; } template && is_integral_ext>> inline constexpr T divfloor(U a, V b) { return T(a) / T(b) - (T(a) % T(b) && (T(a) ^ T(b)) < 0); } template && is_integral_ext>> inline constexpr T safemod(U a, V b) { return T(a) - T(b) * divfloor(a, b); } // https://github.com/miscalculation53/library/tree/wip/template/template_vector.hpp #define ALL(a) (a).begin(), (a).end() template inline T SZ(const V &x) { return x.size(); } #define eb emplace_back #define LMD(x,fx) ([&](const auto &x) { return fx; }) template auto gen_vec(int n, const F &f) { assert(n >= 0); vc res; res.reserve(n); repi(i, n) res.eb(f(i)); return res; } #define GEN_VEC(n,i,fi) (gen_vec(n, LMD(i, fi))) template void fill(V &v, const T &value) { if constexpr (is_assignable_v) std::fill(std::begin(v), std::end(v), value); else for (auto &row : v) fill(row, value); } template vc concat(vc v, const vc &...vs) { (v.insert(v.end(), ALL(vs)), ...); return v; } // https://github.com/miscalculation53/library/tree/wip/template/template_algo.hpp // https://github.com/miscalculation53/library/tree/wip/utils/resolved_infty.hpp // https://github.com/miscalculation53/library/tree/wip/utils/resolved_value.hpp template auto MAX(const V &v) { return *max_element(ALL(v)); } template vc perminv(const vc &p) { if (p.empty()) return {}; const int n = p.size(); vc q(MAX(p) + 1); repi(i, n) if (p[i] >= 0) q[p[i]] = i; return q; } template V reversed(const V &v) { return V(v.rbegin(), v.rend()); } template vvc top(const vvc &a) { if (a.empty()) return {}; const int n = a.size(), m = a[0].size(); vvc b(m, vc(n)); repi(i, n) { assert(SZ(a[i]) == m); repi(j, m) b[j][i] = a[i][j]; } return b; } vstr top(const vstr &a) { vvc a_(a.size()); repi(i, SZ(a)) a_[i] = {ALL(a[i])}; vvc b_ = top(a_); vstr b(b_.size()); repi(i, SZ(b)) b[i] = {ALL(b_[i])}; return b; } template struct has_e0 : false_type {}; template struct has_e0> : true_type {}; template inline constexpr bool has_e0_v = has_e0::value; template struct MonoidAdd { using S = T; static constexpr S op(S a, S b) { return a + b; } static constexpr S e() { if constexpr (has_e0_v) return S::e0(); else return {}; } }; namespace internal { } template vc cuml(const vc &v, int left_index = 0) { const int n = v.size(); vc res(n + 1); res[0] = M::e(); repi(i, n) res[i + 1] = M::op(res[i], v[i]); res.erase(res.begin(), res.begin() + left_index); return res; } template vc cumlsum(const vc &v, int left_index = 0) { return cuml>(v, left_index); } constexpr array DRULgrid = {{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}}; constexpr array DRULplane = {{{0, -1}, {1, 0}, {0, 1}, {-1, 0}}}; // https://github.com/miscalculation53/library/tree/wip/template/template_binsearch.hpp template struct is_random_access_iterator { static constexpr bool value = is_same_v< typename iterator_traits::iterator_category, random_access_iterator_tag >; }; template constexpr bool is_random_access_iterator_v = is_random_access_iterator::value; #define DEFAULT_COMP ranges::less namespace internal { }; // https://github.com/miscalculation53/library/tree/wip/template/template_bit.hpp template inline constexpr ull MASK(T k) { return (1ULL << k) - 1ULL; } inline constexpr ll bit_width(ll x) { return std::bit_width((ull)x); } inline constexpr ll bit_floor(ll x) { return std::bit_floor((ull)x); } inline constexpr ll bit_ceil(ll x) { return std::bit_ceil((ull)x); } inline constexpr ll countr_zero(ll x) { assert(x != 0); return std::countr_zero((ull)x); } inline constexpr ll popcount(ll x) { return std::popcount((ull)x); } inline constexpr bool has_single_bit(ll x) { return std::has_single_bit((ull)x); } inline constexpr ull lsb_pos(ull x) { assert(x != 0); return countr_zero(x); } inline constexpr ull msb_pos(ull x) { assert(x != 0); return bit_width(x) - 1; } inline constexpr ull lsb_mask(ull x) { assert(x != 0); return x & -x; } inline constexpr ull msb_mask(ull x) { assert(x != 0); return bit_floor(x); } inline constexpr bool btest(ull x, uint k) { return (x >> k) & 1; } inline constexpr bool bsubset(ull x, ull y) { return (x & y) == x; } inline constexpr bool bsupset(ull x, ull y) { return (x & y) == y; } inline constexpr ull bsetminus(ull x, ull y) { return x & ~y; } // https://github.com/miscalculation53/library/tree/wip/template/template_inout.hpp // https://github.com/miscalculation53/library/tree/wip/template/template_dump.hpp // https://github.com/miscalculation53/library/tree/wip/template/template_dump_map.hpp #define CPP_DUMP_DEFINE_DATA(...) #define dump(...) ((void)0) #define local(...) #define oj(...) __VA_ARGS__ #define local_oj(a,b) (b) template vc content(queue que); template vc content(priority_queue pque); template auto content(const T &obj); namespace fastio { template struct unsigned_integer { using type = make_unsigned_t; }; template <> struct unsigned_integer { using type = u128; }; template <> struct unsigned_integer { using type = u128; }; template using unsigned_integer_t = typename unsigned_integer::type; static constexpr uint32_t SIZ = 1 << 17; char ibuf[SIZ]; char obuf[SIZ]; char out[100]; uint32_t pil = 0, pir = 0, por = 0; struct Pre { char num[10000][4]; constexpr Pre() : num() { for (int i = 0; i < 10000; i++) { int n = i; for (int j = 3; j >= 0; j--) { num[i][j] = n % 10 | '0'; n /= 10; } } } } constexpr pre; inline void load() { memcpy(ibuf, ibuf + pil, pir - pil); pir = pir - pil + fread(ibuf + pir - pil, 1, SIZ - pir + pil, stdin); pil = 0; if (pir < SIZ) ibuf[pir++] = '\n'; } inline void flush() { fwrite(obuf, 1, por, stdout); por = 0; } void rd1(char &c) { do { if (pil + 1 > pir) load(); c = ibuf[pil++]; } while (c <= ' '); } void rd1(string &x) { x.clear(); while (true) { if (pil == pir) load(); while (pil < pir && ibuf[pil] <= ' ') ++pil; if (pil < pir) break; } while (true) { uint32_t p = pil; while (pil < pir && ibuf[pil] > ' ') ++pil; x.append(ibuf + p, pil - p); if (pil < pir) { ++pil; return; } load(); } } template void rd1_real(T &x) { string s; rd1(s); if constexpr (!is_same_v) { auto [p, ec] = from_chars(s.data(), s.data() + s.size(), x); if (ec == errc{} && p == s.data() + s.size()) return; } if constexpr (is_same_v) x = stold(s); else x = stod(s); } template void rd1_integer(T &x) { using U = unsigned_integer_t; bool minus = false; U val = 0; if constexpr (check_buffer) if (pil + 100 > pir) load(); uint32_t p = pil; while (ibuf[p] < '-') ++p; if constexpr (is_signed::value || is_same_v) { if (ibuf[p] == '-') minus = true, ++p; } while ('0' <= ibuf[p]) val = val * 10 + (ibuf[p++] & 15); pil = p; if constexpr (is_signed::value || is_same_v) { if (minus) { const U min_abs = U(numeric_limits::max()) + 1; x = val == min_abs ? numeric_limits::lowest() : -T(val); } else x = T(val); } else x = T(val); } void rd1(int &x) { rd1_integer(x); } void rd1(ll &x) { rd1_integer(x); } void rd1(i128 &x) { rd1_integer(x); } void rd1(uint &x) { rd1_integer(x); } void rd1(ull &x) { rd1_integer(x); } void rd1(u128 &x) { rd1_integer(x); } void rd1(double &x) { rd1_real(x); } void rd1(long double &x) { rd1_real(x); } template void rd1(tuple &tpl) { apply([](auto &...x) { (rd1(x), ...); }, tpl); } template void rd1(vc &x) { for (auto &d: x) rd1(d); } template void read(T &...x) { if constexpr (sizeof...(T) <= SIZ / 100 && ((!is_same_v && (is_integral_v || is_same_v || is_same_v)) && ...)) { if (pil + 100 * sizeof...(T) > pir) load(); (rd1_integer(x), ...); } else (rd1(x), ...); } void wt1(const char c) { if (por == SIZ) flush(); obuf[por++] = c; } void wt1(string_view s) { while (!s.empty()) { if (por == SIZ) flush(); size_t n = min(s.size(), SIZ - por); memcpy(obuf + por, s.data(), n); por += n; s.remove_prefix(n); } } template void wt1_integer(T x) { if (por > SIZ - 100) flush(); using U = unsigned_integer_t; U ux; if constexpr (is_signed::value || is_same_v) { if (x < 0) obuf[por++] = '-', ux = U(0) - U(x); else ux = U(x); } else ux = x; int outi; for (outi = 96; ux >= 10000; outi -= 4) { memcpy(out + outi, pre.num[ux % 10000], 4); ux /= 10000; } if (ux >= 1000) { memcpy(obuf + por, pre.num[ux], 4); por += 4; } else if (ux >= 100) { memcpy(obuf + por, pre.num[ux] + 1, 3); por += 3; } else if (ux >= 10) { int q = (ux * 103) >> 10; obuf[por] = q | '0'; obuf[por + 1] = (ux - q * 10) | '0'; por += 2; } else obuf[por++] = ux | '0'; memcpy(obuf + por, out + outi + 4, 96 - outi); por += 96 - outi; } template void wt1_real(T x) { if constexpr (!is_same_v) { auto [p, ec] = to_chars(out, out + sizeof(out), x, chars_format::fixed, 15); if (ec == errc{}) { wt1(string_view(out, p)); return; } } ostringstream oss; oss << fixed << setprecision(15) << x; wt1(oss.str()); } void wt1(int x) { wt1_integer(x); } template , int> = 0> void wt1(T x) { wt1_integer(x); } void wt1(i128 x) { wt1_integer(x); } void wt1(u128 x) { wt1_integer(x); } void wt1(double x) { wt1_real(x); } void wt1(long double x) { wt1_real(x); } template void wt1(const pair &val); template void wt1(const tuple &tpl); template void wt1(const array &val); template void wt1(const vector &val); template void write(T &&...x) { (wt1(std::forward(x)), ...); } template void print(T &&...x) { if constexpr (sizeof...(T)) { int i = 0; ((i++ ? wt1(' ') : void(), wt1(std::forward(x))), ...); } wt1('\n'); } } struct Dummy { Dummy() { atexit(fastio::flush); } } dummy; namespace internal { template void READnodump(Ts &...a) { fastio::read(a...); } template void READVECnodump(int n, vc &...v) { (v.resize(n), ...); READnodump(v...); } }; #define READ(...) internal::READnodump(__VA_ARGS__); dump(__VA_ARGS__) #define IN(T,...) T __VA_ARGS__; READ(__VA_ARGS__) #define CHAR(...) IN(char, __VA_ARGS__) #define INT(...) IN(int, __VA_ARGS__) #define LL(...) IN(ll, __VA_ARGS__) #define STR(...) IN(string, __VA_ARGS__) #define ARR(T,n,...) array __VA_ARGS__; READ(__VA_ARGS__) #define READVEC(...) internal::READVECnodump(__VA_ARGS__); dump(__VA_ARGS__) #define READVEC2(...) internal::READVEC2nodump(__VA_ARGS__); dump(__VA_ARGS__) #define VEC(T,n,...) vc __VA_ARGS__; READVEC(n, __VA_ARGS__) #define VEC2(T,n,m,...) vvc __VA_ARGS__; READVEC2(n, m, __VA_ARGS__) #define READJAG(...) internal::READJAGnodump(__VA_ARGS__); dump(__VA_ARGS__) #define JAG(T,n,...) vvc __VA_ARGS__; READJAG(n, __VA_ARGS__) #define ENDL '\n' #define WRITE fastio::write #define PRINT fastio::print #define PRINTEXIT(...) do { PRINT(__VA_ARGS__); exit(0); } while (false) #define PRINTRETURN(...) do { PRINT(__VA_ARGS__); return; } while (false) #define PRINTVEXIT(...) do { PRINTV(__VA_ARGS__); exit(0); } while (false) #define PRINTVRETURN(...) do { PRINTV(__VA_ARGS__); return; } while (false) namespace internal { template auto &tuple_add_impl(A &a, const B &b, const index_sequence) { ((get(a) += get(b)), ...); return a; } }; template tuple &operator+=(tuple &a, const Tp &b) { return internal::tuple_add_impl(a, b, make_index_sequence>>{}); } template void offset(vc &v, const Add &add) { for (auto &vi : v) vi += add; } template array, m> unzip(const vc> &vt) { const size_t n = vt.size(); array, m> tv; tv.fill(vc(n)); for (size_t i = 0; i < n; i++) for (size_t j = 0; j < m; j++) tv[j][i] = vt[i][j]; return tv; } template pair, vc> unzip(const vc> &vt) { const size_t n = vt.size(); pair, vc> tv; tv.first.resize(n), tv.second.resize(n); for (size_t i = 0; i < n; i++) tie(tv.first[i], tv.second[i]) = vt[i]; return tv; } namespace internal { template auto vt_to_tv_impl(V &tv, const Tp &t, index_sequence, size_t index) { ((get(tv)[index] = get(t)), ...); } }; template auto unzip(const vc> &vt) { const size_t n = vt.size(); tuple...> tv; apply([&](auto &...v) { ((v.resize(n)), ...); }, tv); for (size_t i = 0; i < n; i++) internal::vt_to_tv_impl(tv, vt[i], make_index_sequence>{}, i); return tv; } namespace internal { }; #define UNZIP(vt,...) auto [__VA_ARGS__] = unzip(vt) #define ZIP(vt,...) auto vt = internal::zip_vectors(__VA_ARGS__) // https://github.com/miscalculation53/library/tree/wip/template/template_random.hpp mt19937_64 mt; bool randbool(double p) { assert(0 <= p && p <= 1); return bernoulli_distribution(p)(mt); } namespace internal { }; // https://github.com/miscalculation53/library/tree/wip/math/modint/template_modint.hpp // https://github.com/miscalculation53/library/tree/wip/math/modint/modint.hpp // https://github.com/miscalculation53/library/tree/wip/math/modint/modint_internal_static.hpp // https://github.com/miscalculation53/library/tree/wip/utils/larger_int.hpp namespace larger_int_detail { } template struct larger_int { private: static constexpr bool check(); static_assert(check()); public: using type = T; }; #define LARGER_INT(T,U) template <> struct larger_int { using type = U; }; LARGER_INT(signed char, short) LARGER_INT(short, int) LARGER_INT(int, long long) LARGER_INT(long, __int128_t) LARGER_INT(long long, __int128_t) LARGER_INT(unsigned char, unsigned short) LARGER_INT(unsigned short, unsigned int) LARGER_INT(unsigned int, unsigned long long) LARGER_INT(unsigned long, __uint128_t) LARGER_INT(unsigned long long, __uint128_t) #undef LARGER_INT template struct Rational; template struct larger_int> { using type = Rational::type>; }; template using larger_int_t = typename larger_int::type; // https://github.com/miscalculation53/library/tree/wip/math/modint/modint_internal_isprime.hpp namespace internal { template constexpr ll powmod_constexpr(ll x, ll n, T m) { if (m == 1) return 0; using U = make_unsigned_t; using L = larger_int_t; U r = 1, y = safemod(x, m); while (n) { if (n & 1) r = L(r) * y % m; y = L(y) * y % m; n >>= 1; } return r; } template constexpr bool isprime = isprime_constexpr(n); }; namespace internal { template struct policy_static { using mod_type = decltype(M); using value_type = make_unsigned_t; using calc_type = conditional_t<(M <= UINT_MAX), ull, larger_int_t>; static constexpr bool is_prime = isprime_constexpr(M); static constexpr value_type init(value_type v) { return v; } static constexpr mod_type val(value_type v); }; }; // https://github.com/miscalculation53/library/tree/wip/math/modint/modint_internal_barrett32.hpp namespace internal { struct barrett32 { uint m = 0; ull im = 0; barrett32() = default; explicit barrett32(uint m) : m(m), im((ull)(-1) / m + 1) {} uint umod() const { return m; } uint mul(uint a, uint b) const { ull z = a; z *= b; ull x = ull((u128(z) * im) >> 64); ull y = x * m; return uint(z - y + (z < y ? m : 0)); } }; template struct policy_barrett32 { using value_type = uint; using calc_type = ull; using mod_type = int; static constexpr bool is_prime = false; static inline barrett32 reducer{}; static value_type init(value_type v) { return v; } static mod_type val(value_type v); }; }; // https://github.com/miscalculation53/library/tree/wip/math/modint/modint_internal_montgomery64.hpp namespace internal { inline constexpr ull inv64(ull a) { ull x = a; while (a * x != 1) x *= 2 - a * x; return x; } struct montgomery64odd { ull m = 0, im = 0, sq = 0; montgomery64odd() = default; explicit montgomery64odd(ull m) : m(m), im(inv64(m)), sq(-u128(m) % m) {} ull umod() const { return m; } ull reduce(u128 x) const { auto t = (x + u128(m) * (-im * ull(x))) >> 64; if (t >= m) t -= m; return (ull)t; } ull inv_reduce(i128 v) const { return reduce(u128(v % m + m) * sq); } }; struct montgomery64 { ull m = 0, mx = 0, imx = 0, d = 0, q = 0; uint b = 0; montgomery64() = default; explicit montgomery64(ull m) : m(m) { b = countr_zero(m), mx = m >> b; imx = inv64(mx); d = powmod_constexpr((mx + 1) / 2, b, mx); u128 sq = -u128(mx) % mx; q = (1 + (((sq - 1) * d) << b)) % m; } ull umod() const { return m; } ull reduce(u128 x) const { if (b == 0) { auto t = (x + u128(mx) * (-imx * ull(x))) >> 64; if (t >= m) t -= m; return (ull)t; } ull p = x & MASK(b); x = (x >> b) + p * d; ull y = p << (64 - b); auto t = (x + u128(mx) * (imx * (y - ull(x)))) >> (64 - b); if (t >= m) { t -= m; if (t >= m) t -= m; } return (ull)t; } ull inv_reduce(i128 v) const { return reduce(u128(v % m + m) * q); } }; template struct policy_montgomery64_odd { using value_type = ull; using calc_type = u128; using mod_type = ll; static constexpr bool is_prime = false; static inline montgomery64odd reducer{}; static value_type init(value_type v) { return reducer.inv_reduce(v); } static mod_type val(value_type v); }; template struct policy_montgomery64 { using value_type = ull; using calc_type = u128; using mod_type = ll; static constexpr bool is_prime = false; static inline montgomery64 reducer{}; static value_type init(value_type v) { return reducer.inv_reduce(v); } static mod_type val(value_type v); }; }; // https://github.com/miscalculation53/library/tree/wip/math/extgcd.hpp namespace internal { template struct modint_impl { using V = typename Policy::value_type; using M = typename Policy::mod_type; using mint = modint_impl; private: V _v; public: modint_impl(); template >> modint_impl(T v); M val() const; friend mint operator+(const mint &lhs, const mint &rhs) { return mint(lhs) += rhs; } friend mint operator-(const mint &lhs, const mint &rhs) { return mint(lhs) -= rhs; } friend mint operator*(const mint &lhs, const mint &rhs) { return mint(lhs) *= rhs; } friend mint operator/(const mint &lhs, const mint &rhs) { return mint(lhs) /= rhs; } friend bool operator==(const mint &lhs, const mint &rhs) { return lhs._v == rhs._v; } friend bool operator!=(const mint &lhs, const mint &rhs) { return lhs._v != rhs._v; } friend M safe_hash_key(const mint &x) { return x.val(); } friend void rd1(mint &x) { long long a; fastio::rd1(a); x = a; } friend void wt1(const mint &x) { fastio::wt1(x.val()); } }; }; template using static_modint32 = internal::modint_impl>; template using dynamic_modint32 = internal::modint_impl>; template using dynamic_modint64_odd = internal::modint_impl>; template using dynamic_modint64 = internal::modint_impl>; using modint998244353 = static_modint32<998244353>; template struct is_modint : std::false_type { }; template struct is_modint> : std::true_type { }; template inline constexpr bool is_modint_v = is_modint::value; template struct is_static_modint : false_type {}; template struct is_static_modint, PowInv>> : true_type {}; template struct is_static_modint, PowInv>> : true_type {}; template inline constexpr bool is_static_modint_v = is_static_modint::value; template struct is_dynamic_modint : false_type {}; template struct is_dynamic_modint> : true_type {}; template struct is_dynamic_modint> : true_type {}; template struct is_dynamic_modint> : true_type {}; template inline constexpr bool is_dynamic_modint_v = is_dynamic_modint::value; // https://github.com/miscalculation53/library/tree/wip/math/modint/power_table.hpp // https://github.com/miscalculation53/library/tree/wip/math/modint/binomial.hpp template struct Binomial { private: inline static decltype(T::mod()) mod; public: inline static vc fac_, finv_, inv_; }; // https://github.com/miscalculation53/library/tree/wip/math/modint/stom.hpp // https://github.com/miscalculation53/library/tree/wip/math/modint/to_rational.hpp // https://github.com/miscalculation53/library/tree/wip/math/svp2d.hpp namespace cpp_dump { template struct rat_value { T p, q; friend ostream &operator<<(ostream &os, const rat_value &x) { os << x.p; if (x.q != 1) os << '/' << x.q; return os; } }; template inline constexpr bool rat_is_map = false; template inline constexpr bool rat_is_map> = true; template inline constexpr bool rat_is_map> = true; template inline constexpr bool rat_is_map> = true; template inline constexpr bool rat_is_map> = true; struct rat_closure : std::ranges::range_adaptor_closure { }; constexpr rat_closure rat() { return rat_closure{}; } } using mint = modint998244353; // using mint = modint1000000007; // using mint = static_modint<1000000000>; // using mint = modint; void init() { oj(mt.seed(random_device()())); } // https://github.com/miscalculation53/library/tree/wip/graph/tree/merge_tree.hpp // https://github.com/miscalculation53/library/tree/wip/ds/uf/uf.hpp template struct UnionFind { friend UFData; protected: vc par; vc vdat; public: typename UFData::GData gdat; UnionFind() {} void reset(int n) { assert(n >= 0); par.assign(n, -1); vdat.resize(n); gdat = typename UFData::GData(n); repi(i, n) vdat[i] = typename UFData::VData(i); } virtual int leader(int x) { assert(0 <= x && x < SZ(par)); if (par[x] < 0) return x; if constexpr (compress) return par[x] = leader(par[x]); else return leader(par[x]); } template I size(int x) { return -par[leader(x)]; } bool same(int x, int y) { return leader(x) == leader(y); } template I merge(int x, int y, const typename UFData::EWeight &w = 1) { x = leader(x), y = leader(y); if (x == y) { UFData::add_edge_same(*this, x, w); return x; } if (-par[x] < -par[y]) swap(x, y); par[x] += par[y], par[y] = x; UFData::add_edge_diff(*this, x, y, w); return x; } }; template struct UFDataEmpty { struct VData { VData() {} VData(int) {} }; struct GData { GData() {} GData(int) {} }; using EWeight = EWeight_; template static void add_edge_diff(UF &, int, int, EWeight) {} template static void add_edge_same(UF &, int, EWeight) {} }; struct MergeTree { private: UnionFind> uf; vc top, par; public: explicit MergeTree(int n = 0) { assert(n >= 0); uf.reset(n); top.resize(n); iota(ALL(top), 0); par.reserve(size_t(n) * 2); par.assign(n, -1); } vc parents() const { return par; } bool same(int u, int v) { return uf.same(u, v); } int merge(int u, int v) { int x = uf.leader(u), y = uf.leader(v); if (x == y) return -1; int a = top[x], b = top[y], z = par.size(); par.eb(-1); par[a] = par[b] = z; int r = uf.merge(x, y); top[r] = z; return z; } }; // https://github.com/miscalculation53/library/tree/wip/graph/tree/rooted_tree.hpp struct RootedTree { protected: static const int MSK = 1 << 30; int n; vc p_head, dep, pre, post, preinv; inline int internal_head(int v) const { return (p_head[v] & MSK) ? v : p_head[v]; } inline int parent_of_head(int hv) const { return p_head[hv] & ~MSK; } void build(int rt, const vc &siz, vc &max_chi_siz) { vc ord(n); { vc cnt(n + 1); repi(i, n) cnt[siz[i]]++; cnt = cumlsum(cnt); repi(i, n) ord[n - 1 - (cnt[siz[i]]++)] = i; } { p_head[rt] = rt | MSK, post[rt] = n; vc add(n, 1); repi(i, 1, n) { int v = ord[i]; int p = p_head[v]; dep[v] = dep[p] + 1; pre[v] = pre[p] + add[p]; add[p] += siz[v]; post[v] = pre[v] + siz[v]; if (max_chi_siz[p] == siz[v]) { max_chi_siz[p] = 0; p_head[v] = internal_head(p_head[v]); } else p_head[v] |= MSK; } preinv = perminv(pre); } } public: RootedTree() {} template RootedTree(int n, const vc &par) : n(n), p_head(n), dep(n), pre(n), post(n), preinv(n) { assert(n >= 1); assert(SZ(par) == n); int rt = -1; vc deg(n), siz(n, 1), max_chi_siz(n); repi(i, n) { if (par[i] < 0 || par[i] == i) { assert(rt == -1 && "There are more than two roots"); rt = i; } else { p_head[i] = par[i]; deg[par[i]]++; } } assert(rt != -1 && "There is no root"); repi(i, n) { int v = i; while (v != rt && deg[v] == 0) { int p = p_head[v]; deg[p]--, deg[v]--; siz[p] += siz[v]; chmax(max_chi_siz[p], siz[v]); v = p; } } build(rt, siz, max_chi_siz); } template I size() const { return n; } int root() const { return preinv[0]; } int parent(int v) const { assert(0 <= v && v < n); assert(v != root()); int ph = p_head[v]; if (ph & MSK) return ph & ~MSK; else return preinv[pre[v] - 1]; } vc parents() const { vc par(n, -1); int rt = root(); repi(v, n) if (v != rt) par[v] = parent(v); return par; } int head(int v) const { assert(0 <= v && v < n); return internal_head(v); } int preorder(int v) const { assert(0 <= v && v < n); return pre[v]; } int postorder(int v) const { assert(0 <= v && v < n); return post[v]; } int preorder_select(int i) const { assert(0 <= i && i < n); return preinv[i]; } vc path_to_root(int v) const { assert(0 <= v && v < n); vc res = {v}; res.reserve(dep[v] + 1); int rt = root(); while (v != rt) { int p = parent(v); res.eb(p); v = p; } return res; } vc path(int u, int v) const { assert(0 <= u && u < n); assert(0 <= v && v < n); vc pu = {u}, pv = {v}; while (u != v) { if (dep[u] > dep[v]) { int p = parent(u); pu.eb(p); u = p; } else { int p = parent(v); pv.eb(p); v = p; } } pv.pop_back(); return concat(pu, reversed(pv)); } const vc &top_down_vertices() const { return preinv; } vc bottom_up_vertices() const { return reversed(top_down_vertices()); } pair> dfs_ordered_vertices() const { string bp(2 * (n - 1), '?'); vc vs(2 * (n - 1) + 1); int rt = root(); vs[0] = rt; repi(v, n) { if (v == rt) continue; int p = parent(v); int in_idx = 2 * pre[v] - dep[v] - 1; int out_idx = 2 * post[v] - dep[v] - 2; bp[in_idx] = '(', vs[in_idx + 1] = v; bp[out_idx] = ')', vs[out_idx + 1] = p; } return {bp, vs}; } class ChildIterator; class ChildRange; class ChildIterator { private: const RootedTree* t; int cur; friend class RootedTree; friend class ChildRange; ChildIterator(const RootedTree* t, int cur) : t(t), cur(cur) {} public: using iterator_category = std::input_iterator_tag; using value_type = int; using difference_type = std::ptrdiff_t; using pointer = int*; using reference = int; int operator*() const { return t->preinv[cur]; } void operator++() { cur = t->post[t->preinv[cur]]; } bool operator!=(const ChildIterator& r) const { return cur != r.cur; } bool operator==(const ChildIterator& r) const { return cur == r.cur; } }; class ChildRange { private: const RootedTree* t; int cur, end_pos; friend class RootedTree; ChildRange(const RootedTree* t, int cur, int end_pos) : t(t), cur(cur), end_pos(end_pos) {} public: ChildIterator begin() const { return ChildIterator(t, cur); } ChildIterator end() const { return ChildIterator(t, end_pos); } bool empty() const { return cur == end_pos; } vc to_v() const { return vc(begin(), end()); } }; int heavy_child(int v) const { assert(0 <= v && v < n); if (post[v] - pre[v] == 1) return -1; return preinv[pre[v] + 1]; } ChildRange children(int v) const { assert(0 <= v && v < n); return {this, pre[v] + 1, post[v]}; } ChildRange light_children(int v) const { assert(0 <= v && v < n); int cur = pre[v] + 1; if (cur < post[v]) { cur = post[preinv[cur]]; } return {this, cur, post[v]}; } pair parent_child(int u, int v) const { assert(0 <= u && u < n); assert(0 <= v && v < n); return dep[u] < dep[v] ? pair{u, v} : pair{v, u}; } int lca(int u, int v) const { assert(0 <= u && u < n); assert(0 <= v && v < n); while (true) { int hu = internal_head(u), hv = internal_head(v); if (hu == hv) break; if (dep[hu] > dep[hv]) swap(u, v), swap(hu, hv); v = parent_of_head(hv); } return dep[u] < dep[v] ? u : v; } bool is_ancestor(int u, int v) const { assert(0 <= u && u < n); assert(0 <= v && v < n); return pre[u] <= pre[v] && pre[v] < post[u]; } template pair first_ancestor(int v, const Pred &pred) const { assert(0 <= v && v < n); int rt = root(), child = -1; while (true) { int h = internal_head(v); if (pred(h)) { int ok = pre[h], ng = pre[v] + 1; while (ng - ok > 1) { int mid = ok + (ng - ok) / 2; if (pred(preinv[mid])) ok = mid; else ng = mid; } return {ok < pre[v] ? preinv[ok + 1] : child, preinv[ok]}; } if (h == rt) return {rt, -1}; child = h; v = parent_of_head(h); } } int la(int v, int k) const { assert(0 <= v && v < n); assert(0 <= k); if (k > dep[v]) return -1; while (true) { int hv = internal_head(v); if (k <= dep[v] - dep[hv]) break; k -= dep[v] - dep[hv] + 1; v = parent_of_head(hv); } return preinv[pre[v] - k]; } int jump(int u, int v, int k) const { assert(0 <= u && u < n); assert(0 <= v && v < n); assert(0 <= k); int l = lca(u, v); int d_ul = dep[u] - dep[l]; int d_vl = dep[v] - dep[l]; if (k > d_ul + d_vl) return -1; if (k <= d_ul) return la(u, k); return la(v, d_ul + d_vl - k); } pair subtree_interval(int v, bool edge = false) const { return {pre[v] + edge, post[v]}; } class PathRange { private: static constexpr int capacity = 2 * numeric_limits::digits; array, capacity> intervals; int count = 0; friend class RootedTree; PathRange() = default; public: using iterator = decltype(intervals)::const_iterator; iterator begin() const { return intervals.begin(); } iterator end() const { return intervals.begin() + count; } int size() const { return count; } bool empty() const { return count == 0; } vc> to_v() const { return {begin(), end()}; } }; PathRange path_query(int u, int v, bool edge = false) const { assert(0 <= u && u < n); assert(0 <= v && v < n); PathRange res; int down_begin = PathRange::capacity; while (true) { int hu = internal_head(u), hv = internal_head(v); if (hu == hv) break; if (dep[hu] > dep[hv]) { res.intervals[res.count++] = {pre[hu], pre[u] + 1, true}; u = parent_of_head(hu); } else { res.intervals[--down_begin] = {pre[hv], pre[v] + 1, false}; v = parent_of_head(hv); } } if (dep[u] > dep[v]) { int l = pre[v] + edge; int r = pre[u] + 1; if (l < r) res.intervals[res.count++] = {l, r, true}; } else { int l = pre[u] + edge; int r = pre[v] + 1; if (l < r) res.intervals[res.count++] = {l, r, false}; } while (down_begin < PathRange::capacity) res.intervals[res.count++] = res.intervals[down_begin++]; return res; } }; // https://github.com/miscalculation53/library/tree/wip/ds/meldable_set.hpp struct MeldableSetPool { class Set; private: using Root = int; static constexpr Root null = -1; struct Node { ll count; union { ull bits; array child; }; explicit Node(ull bits) : count(__builtin_popcountll(bits)), bits(bits) {} Node(Root left, Root right, ll count) : count(count), child{left, right} {} }; ll n = 0; int height = 0; vc nodes; static ull low_mask(int k) { return k == 64 ? ~0ULL : (1ULL << k) - 1; } ll count_of(Root root) const { return root == null ? 0 : nodes[root].count; } void check_root(Root root) const { assert(root == null || (0 <= root && root < SZ(nodes))); } void pull(Root root) { nodes[root].count = count_of(nodes[root].child[0]) + count_of(nodes[root].child[1]); } Root make_path(ull key, int h) { Root root = nodes.size(); nodes.eb(1ULL << (key & 63)); key >>= 6; repi(i, h) { Root parent = nodes.size(); if ((key >> i) & 1) nodes.eb(null, root, 1); else nodes.eb(root, null, 1); root = parent; } return root; } Root insert_impl(Root root, ull key, int h, bool &inserted) { if (root == null) { inserted = true; return make_path(key, h); } if (h == 0) { ull bit = 1ULL << (key & 63); inserted = !(nodes[root].bits & bit); nodes[root].bits |= bit; nodes[root].count += inserted; return root; } int b = (key >> (h + 5)) & 1; Root child = insert_impl(nodes[root].child[b], key, h - 1, inserted); nodes[root].child[b] = child; pull(root); return root; } Root erase_impl(Root root, ull key, int h, bool &erased) { if (root == null) return null; if (h == 0) { ull bit = 1ULL << (key & 63); erased = (nodes[root].bits & bit) != 0; nodes[root].bits &= ~bit; nodes[root].count -= erased; } else { int b = (key >> (h + 5)) & 1; nodes[root].child[b] = erase_impl(nodes[root].child[b], key, h - 1, erased); pull(root); } return nodes[root].count == 0 ? null : root; } Root merge_impl(Root a, Root b, int h) { if (a == null) return b; if (b == null) return a; if (h == 0) { nodes[a].bits |= nodes[b].bits; nodes[a].count = __builtin_popcountll(nodes[a].bits); } else { nodes[a].child[0] = merge_impl(nodes[a].child[0], nodes[b].child[0], h - 1); nodes[a].child[1] = merge_impl(nodes[a].child[1], nodes[b].child[1], h - 1); pull(a); } return a; } Root clone_impl(Root root, int h) { if (root == null) return null; Node node = nodes[root]; Root res = nodes.size(); nodes.eb(node); if (h > 0) { Root left = clone_impl(node.child[0], h - 1); Root right = clone_impl(node.child[1], h - 1); nodes[res].child = {left, right}; } return res; } public: explicit MeldableSetPool(ll n = 0, size_t expected_insertions = 0) : n(n) { assert(n >= 0); ull blocks = (ull(n) + 63) / 64; while ((1ULL << height) < blocks) height++; nodes.reserve(expected_insertions * (height + 1)); } ll universe_size() const { return n; } size_t node_count() const { return nodes.size(); } void reserve(size_t count) { nodes.reserve(count); } private: ll size(Root root) const { check_root(root); return count_of(root); } bool empty(Root root) const { check_root(root); return root == null; } Root singleton(ll key) { assert(0 <= key && key < n); return make_path(ull(key), height); } bool contains(Root root, ll key) const { check_root(root); assert(0 <= key && key < n); for (int h = height; h > 0 && root != null; h--) root = nodes[root].child[(ull(key) >> (h + 5)) & 1]; return root != null && ((nodes[root].bits >> (key & 63)) & 1); } bool insert(Root &root, ll key) { check_root(root); assert(0 <= key && key < n); bool inserted = false; root = insert_impl(root, ull(key), height, inserted); return inserted; } bool erase(Root &root, ll key) { check_root(root); assert(0 <= key && key < n); bool erased = false; root = erase_impl(root, ull(key), height, erased); return erased; } void merge(Root &a, Root &b) { check_root(a), check_root(b); if (&a == &b) return; assert(a == null || b == null || a != b); a = merge_impl(a, b, height); b = null; } Root clone(Root root) { check_root(root); return clone_impl(root, height); } ll lt_cnt(Root root, ll key) const { check_root(root); if (key <= 0) return 0; if (key >= n) return count_of(root); ll res = 0; for (int h = height; h > 0 && root != null; h--) { int b = (ull(key) >> (h + 5)) & 1; if (b) res += count_of(nodes[root].child[0]); root = nodes[root].child[b]; } if (root != null) res += __builtin_popcountll(nodes[root].bits & low_mask(key & 63)); return res; } ll leq_cnt(Root root, ll key) const { return key >= n - 1 ? size(root) : lt_cnt(root, key + 1); } ll geq_cnt(Root root, ll key) const { return size(root) - lt_cnt(root, key); } ll gt_cnt(Root root, ll key) const { return size(root) - leq_cnt(root, key); } ll count(Root root, ll l, ll r) const { assert(0 <= l && l <= r && r <= n); return lt_cnt(root, r) - lt_cnt(root, l); } ll kth(Root root, ll k) const { check_root(root); assert(0 <= k && k < count_of(root)); ull block = 0; for (int h = height; h > 0; h--) { ll left = count_of(nodes[root].child[0]); int b = k >= left; if (b) k -= left; root = nodes[root].child[b]; block = (block << 1) | b; } ull bits = nodes[root].bits; int offset = 0; for (int step = 32; step > 0; step >>= 1) { int left = __builtin_popcountll(bits & low_mask(step)); if (k >= left) { k -= left; bits >>= step; offset += step; } } return ll((block << 6) + offset); } ll geq_min(Root root, ll key) const { ll k = lt_cnt(root, key); return k == size(root) ? n : kth(root, k); } ll leq_max(Root root, ll key) const { ll k = leq_cnt(root, key); return k == 0 ? -1 : kth(root, k - 1); } ll gt_min(Root root, ll key) const { return key >= n - 1 ? n : geq_min(root, key + 1); } ll lt_max(Root root, ll key) const { return key <= 0 ? -1 : leq_max(root, key - 1); } ll min_element(Root root) const { return geq_min(root, 0); } ll max_element(Root root) const { return leq_max(root, n - 1); } template void enumerate(Root root, ll l, ll r, const F &f) const; vc content(Root root) const { vc res; res.reserve(size(root)); enumerate(root, 0, n, [&](ll key) { res.eb(key); }); return res; } class const_iterator { friend class Set; const MeldableSetPool *sets = nullptr; Root root = null; ll key = 0; const_iterator(const MeldableSetPool *sets, Root root, ll key) : sets(sets), root(root), key(key) {} public: using iterator_category = input_iterator_tag; using value_type = ll; using difference_type = ptrdiff_t; using reference = ll; using pointer = const ll *; const_iterator() = default; ll operator*() const { return key; } const ll *operator->() const { return &key; } const_iterator &operator++() { key = sets->gt_min(root, key); return *this; } const_iterator operator++(int) { auto old = *this; ++*this; return old; } bool operator==(const const_iterator &other) const { return sets == other.sets && root == other.root && key == other.key; } bool operator!=(const const_iterator &other) const { return !(*this == other); } }; void clear(Root &root) { check_root(root); root = null; } public: class Set { friend struct MeldableSetPool; MeldableSetPool *sets; Root root; Set(MeldableSetPool *sets, Root root) : sets(sets), root(root) {} public: Set(const Set &) = delete; Set &operator=(const Set &) = delete; Set(Set &&other) noexcept : sets(other.sets), root(exchange(other.root, null)) {} Set &operator=(Set &&other) noexcept { if (this != &other) { sets = other.sets; root = exchange(other.root, null); } return *this; } ll universe_size() const { return sets->universe_size(); } ll size() const { return sets->size(root); } bool empty() const { return sets->empty(root); } bool contains(ll key) const { return sets->contains(root, key); } bool insert(ll key) { return sets->insert(root, key); } bool erase(ll key) { return sets->erase(root, key); } void merge(Set &other) { assert(sets == other.sets); sets->merge(root, other.root); } Set clone() const { return Set(sets, sets->clone(root)); } ll lt_cnt(ll key) const { return sets->lt_cnt(root, key); } ll leq_cnt(ll key) const { return sets->leq_cnt(root, key); } ll geq_cnt(ll key) const { return sets->geq_cnt(root, key); } ll gt_cnt(ll key) const { return sets->gt_cnt(root, key); } ll count(ll l, ll r) const { return sets->count(root, l, r); } ll kth(ll k) const { return sets->kth(root, k); } ll geq_min(ll key) const { return sets->geq_min(root, key); } ll gt_min(ll key) const { return sets->gt_min(root, key); } ll leq_max(ll key) const { return sets->leq_max(root, key); } ll lt_max(ll key) const { return sets->lt_max(root, key); } ll min_element() const { return sets->min_element(root); } ll max_element() const { return sets->max_element(root); } template void enumerate(ll l, ll r, const F &f) const; vc content() const { return sets->content(root); } using iterator = MeldableSetPool::const_iterator; using const_iterator = MeldableSetPool::const_iterator; iterator begin() const { return iterator(sets, root, min_element()); } iterator end() const { return iterator(sets, root, universe_size()); } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } void clear() { sets->clear(root); } void swap(Set &other) noexcept { std::swap(sets, other.sets), std::swap(root, other.root); } friend void swap(Set &a, Set &b) noexcept { a.swap(b); } }; Set make_set() { return Set(this, null); } Set make_set(ll key) { return Set(this, singleton(key)); } void clear() { nodes.clear(); } }; void main2() { LL(N, M, Q); VEC(ll, N, A); VEC(tlll, M, UVW); offset(UVW, tlll{-1, -1, 0}); ranges::sort(UVW, {}, LMD(t, get<2>(t))); UNZIP(UVW, U, V, W); vl ws(N, 0); MergeTree mg(N); fec([ u, v, w ] : UVW) { if (mg.same(u, v)) continue; mg.merge(u, v); ws.eb(w); } const ll K = mg.parents().size(); dump(mg.parents() | cp::index()); RootedTree T(K, mg.parents()); MeldableSetPool pool(N + 1, N); auto sts = GEN_VEC(K, v, pool.make_set()); vl cnt(K); rep(v, N) { sts[v].insert(A[v]); cnt[v] = 1; } rep(v, N, K) { auto chi = T.children(v).to_v(); swap(sts[v], sts[chi[0]]); sts[v].merge(sts[chi[1]]); cnt[v] = sts[v].size(); } dump(cnt | cp::index()); dump(ws | cp::index()); rep(_, Q) { LL(s, c); s--; auto [u, v] = T.first_ancestor(s, LMD(v, cnt[v] >= c)); dump(s, u, v); PRINT(v == -1 ? -1 : ws[v]); } } void test() { } // https://github.com/miscalculation53/library/tree/wip/template/template_main.hpp template struct Main { Main() { cauto CERR = [](string val, string color) { string s = "\033[" + color + "m" + val + "\033[m"; }; CERR("\n[FAST_IO]\n\n", "32"); cout << fixed << setprecision(20); init(); CERR("\n[SINGLE_TESTCASE]\n\n", "36"); main2(); } }; Main main_dummy; int main() {}