// https://github.com/miscalculation53/library #define SINGLE_TESTCASE // #define MULTI_TESTCASE // #define AOJ_TESTCASE #ifndef LOCAL #define FAST_IO // #define FAST_CIO // #define INTERACTIVE #endif #define INF 4'000'000'000'000'000'037LL #define EPS 1e-11 #line 30 #include using namespace std; #if __cplusplus > 202002L && defined(__STDCPP_FLOAT128_T__) #include using f128 = std::float128_t; #elif defined(__SIZEOF_FLOAT128__) using f128 = __float128; #else #error "f128 requires a compiler with IEEE binary128 support, such as GCC on x86_64." #endif #define LIBRARY_HAS_FLOAT128 1 #include using namespace std; using ld = decltype(EPS); using ll = long long; using uint = unsigned int; using ull = unsigned long long; using pll = pair; using tlll = tuple; using tllll = tuple; #define vc vector template using vvc = vc>; template using vvvc = vc>>; using vb = vc; using vl = vc; using vpll = vc; using vtlll = vc; using vtllll = vc; using vstr = vc; using vvb = vvc; using vvl = vvc; template using pql = priority_queue, greater>; template using pqg = priority_queue; using i128 = __int128_t; using u128 = __uint128_t; #define cauto const auto #line 103 //! https://gcc.gnu.org/onlinedocs/libquadmath/Math-Library-Routines.html #line 289 i128 stoi128(const string &s) { const bool neg = s.front() == '-'; u128 res = 0; for (size_t i = size_t(neg); i < s.size(); i++) res = 10 * res + unsigned(s[i] - '0'); if (neg) return -i128(res - 1) - 1; return i128(res); } inline string u128tos(u128 x) { string res; do { res += char('0' + x % 10); x /= 10; } while (x > 0); reverse(res.begin(), res.end()); return res; } string i128tos(i128 x) { return x < 0 ? "-" + u128tos(u128(-(x + 1)) + 1) : u128tos(u128(x)); } istream &operator>>(istream &is, i128 &a) { string s; if (!(is >> s)) return is; a = stoi128(s); return is; } ostream &operator<<(ostream &os, const i128 &a) { os << i128tos(a); return os; } #line 337 #define overload4(_1, _2, _3, _4, name, ...) name #define LIBRARY_REPEAT_LOOP(T, i, l, r, d) \ for (auto [i, library_repeat_end, library_repeat_step] = array{T(l), T(r), T(d)}; \ library_repeat_step > 0 ? i < library_repeat_end : i > library_repeat_end; \ i += library_repeat_step) #define rep1(i, n) LIBRARY_REPEAT_LOOP(ll, i, 0, n, 1) #define rep(...) overload4(__VA_ARGS__, rep3, rep2, rep1)(__VA_ARGS__) #define repi1(i, n) LIBRARY_REPEAT_LOOP(int, i, 0, n, 1) #define repi2(i, l, r) LIBRARY_REPEAT_LOOP(int, i, l, r, 1) #define repi(...) overload4(__VA_ARGS__, repi3, repi2, repi1)(__VA_ARGS__) #define fe(...) for (auto __VA_ARGS__) #define fec(...) for (cauto &__VA_ARGS__) #line 408 template constexpr pair &operator+=(pair &a, const P &b) { a.first += b.first; a.second += b.second; return a; } template constexpr pair operator+(pair a, const P &b) { return a += b; } template constexpr pair &operator-=(pair &a, const P &b) { a.first -= b.first; a.second -= b.second; return a; } template constexpr pair operator-(pair a, const P &b) { return a -= b; } template constexpr pair operator-(pair a) { a.first = -a.first; a.second = -a.second; return a; } template constexpr array &operator+=(array &a, const A &b) { for (size_t i = 0; i < n; i++) a[i] += b[i]; return a; } template constexpr array operator+(array a, const A &b) { return a += b; } template constexpr array &operator-=(array &a, const A &b) { for (size_t i = 0; i < n; i++) a[i] -= b[i]; return a; } template constexpr array operator-(array a, const A &b) { return a -= b; } template constexpr array operator-(array a) { for (auto &ai : a) ai = -ai; return a; } namespace internal { template constexpr auto &tuple_add_impl(A &a, const B &b, const index_sequence) ; template constexpr auto &tuple_sub_impl(A &a, const B &b, const index_sequence) ; template constexpr auto &tuple_neg_impl(A &a, const index_sequence) ; }; template constexpr tuple &operator+=(tuple &a, const Tp &b) { return internal::tuple_add_impl(a, b, make_index_sequence>>{}); } template constexpr tuple operator+(tuple a, const Tp &b) { return a += b; } template constexpr tuple &operator-=(tuple &a, const Tp &b) { return internal::tuple_sub_impl(a, b, make_index_sequence>>{}); } template constexpr tuple operator-(tuple a, const Tp &b) { return a -= b; } template constexpr tuple operator-(tuple a) { internal::tuple_neg_impl(a, make_index_sequence{}); return a; } #line 512 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; #line 531 template struct make_unsigned_ext { using type = make_unsigned_t; }; template <> struct make_unsigned_ext { using type = u128; }; template <> struct make_unsigned_ext { using type = u128; }; template using make_unsigned_ext_t = typename make_unsigned_ext::type; template struct make_signed_ext { using type = make_signed_t; }; template <> struct make_signed_ext { using type = i128; }; template <> struct make_signed_ext { using type = i128; }; template using make_signed_ext_t = typename make_signed_ext::type; template constexpr bool is_negative(T x) { static_assert(is_integral_ext); if constexpr (is_signed_ext) return x < 0; return false; } template > struct unsigned_arithmetic { using type = T; }; template struct unsigned_arithmetic { static_assert(!is_same_v); using type = common_type_t>; }; template using unsigned_arithmetic_t = typename unsigned_arithmetic::type; #line 633 namespace default_infty_detail { template struct is_product : false_type {}; template struct is_product> : true_type {}; template struct is_product> : true_type {}; template struct is_product> : true_type {}; template struct has_infty : false_type {}; template struct has_infty> : true_type {}; template inline constexpr bool unsupported = false; } #line 701 template inline bool chmin(T &a, U b) ; namespace template_math_detail { #line 733 } #line 763 template && is_integral_ext>> inline constexpr T safemod(U a, V b) { const T x = T(a), y = T(b); if constexpr (is_signed_ext) if (y == T(-1)) return T(0); const T r = x % y; return r != T(0) && is_negative(x) != is_negative(y) ? T(r + y) : r; } #line 897 //! https://misawa.github.io/others/avoid_errors/techniques_to_avoid_errors.html #line 968 #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) ; namespace template_vector_detail { template struct nested_vector { using type = vc::type>; }; template struct nested_vector { using type = T; }; #line 1024 } #line 1039 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); } #line 1088 template vc concat(const vvc &vs) { vc res; for (cauto &v : vs) res.insert(res.end(), ALL(v)); return res; } template vc concat(const vc &v) { return v; } template vc concat(vc v, const vc &...vs) { (v.insert(v.end(), ALL(vs)), ...); return v; } #line 1158 template constexpr decltype(auto) resolved_infty() ; #line 1175 namespace internal { template struct HasMonoidPow : false_type {}; template struct HasMonoidPow(), declval()))>> : true_type {}; } namespace internal_monoid_power { #line 1211 } #line 1337 template V reversed(const V &v) { return V(v.rbegin(), v.rend()); } #line 1385 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 {}; } template () * declval())> static constexpr S pow(const S &a, I k) { return a * k; } }; template struct MonoidMin { using S = T; static constexpr S op(S a, S b) { return min(a, b); } static constexpr decltype(auto) e() { return resolved_infty(); } template static constexpr S pow(const S &a, I k) { return k == 0 ? e() : a; } }; template struct MonoidMax { using S = T; static constexpr S op(S a, S b) { return max(a, b); } static constexpr S e() { return -resolved_infty(); } template static constexpr S pow(const S &a, I k) { return k == 0 ? e() : a; } }; #line 1467 template vc cumlsum(const vc &v, int left_index = 0) ; #line 1509 constexpr array DRULgrid = {{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}}; constexpr array DRULplane = {{{0, -1}, {1, 0}, {0, 1}, {-1, 0}}}; 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; #line 1581 #define DEFAULT_COMP ranges::less #line 1691 namespace internal { }; #line 1784 template inline constexpr ull MASK(T k) { return (1ULL << k) - 1ULL; } #line 1805 inline constexpr ll countr_zero(ll x) { assert(x != 0); return std::countr_zero((ull)x); } #line 1936 #define CPP_DUMP_DEFINE_DATA(...) #define dump(...) ((void)0) #define local(...) #define oj(...) __VA_ARGS__ template vc content(queue que) { vc res; while (!que.empty()) { res.eb(que.front()); que.pop(); } return res; } template vc content(priority_queue pque) { vc res; while (!pque.empty()) { res.eb(pque.top()); pque.pop(); } return res; } template auto content(const T &obj) { return obj.content(); } #line 2001 namespace fastio { constexpr uint32_t SIZ = 1 << 17; inline char ibuf[SIZ + 1], obuf[SIZ]; inline uint32_t pil = 0, pir = 0, por = 0; __attribute__((noinline)) inline void load() { const uint32_t remaining = pir - pil; if (remaining && pil) memmove(ibuf, ibuf + pil, remaining); pil = 0; pir = remaining + uint32_t(fread(ibuf + remaining, 1, SIZ - remaining, stdin)); ibuf[pir] = '\x7f'; } inline bool ascii_space(unsigned char c) { return c == ' ' || unsigned(c - '\t') < 5; } inline void find_token() { for (;;) { const char *p = ibuf + pil; const char *end = ibuf + pir; while (ascii_space(*p)) ++p; pil = uint32_t(p - ibuf); if (p != end) return; load(); if (!pir) abort(); } } __attribute__((noinline)) inline void flush() { size_t written = 0; while (written < por) { const size_t n = fwrite(obuf + written, 1, por - written, stdout); if (!n) abort(); written += n; } por = 0; } inline void append_bytes(const char *data, size_t size) { while (size) { const size_t n = min(size, size_t(SIZ - por)); memcpy(obuf + por, data, n); por += uint32_t(n); data += n; size -= n; if (por == SIZ) flush(); } } inline void append_char(char c) { if (por == SIZ) flush(); obuf[por++] = c; } template using integer_magnitude = conditional_t<(sizeof(T) > sizeof(ull)), u128, conditional_t<(sizeof(T) > sizeof(uint)), ull, uint>>; inline constexpr uint powers_of_ten[8] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; template __attribute__((always_inline)) inline void read_wide_integer_tail( U &value, const char *&p, uint64_t columns, uint64_t stop) ; #line 2102 template __attribute__((always_inline)) inline void rd1_integer(T &x) { using U = integer_magnitude; const char *p = ibuf + pil; for (;;) { while (ascii_space(*p)) ++p; if (p != ibuf + pir) break; pil = pir; load(); if (!pir) abort(); p = ibuf; } bool negative = false; if (*p == '+') ++p; else if constexpr (numeric_limits::is_signed) { if (*p == '-') negative = true, ++p; } U value = 0; for (;;) { while (size_t(ibuf + pir - p) >= 8) { uint64_t columns; memcpy(&columns, p, 8); const uint64_t stop = ((columns + 0x4646464646464646ULL) | (columns - 0x3030303030303030ULL)) & 0x8080808080808080ULL; if (stop) { if constexpr (sizeof(U) > sizeof(ull)) { read_wide_integer_tail(value, p, columns, stop); goto integer_complete; } else { if (stop & 0x80808080ULL) { if (!(stop & 0x808080ULL)) { value = value * 1000 + uint(columns & 15) * 100 + uint(columns >> 8 & 15) * 10 + uint(columns >> 16 & 15); p += 3; } else if (!(stop & 0x8080ULL)) { value = value * 100 + uint(columns & 15) * 10 + uint(columns >> 8 & 15); p += 2; } else if (!(stop & 0x80ULL)) { value = value * 10 + uint(columns & 15); ++p; } goto integer_complete; } break; } } columns &= 0x0f0f0f0f0f0f0f0fULL; const uint64_t pairs = (columns & 0x00ff00ff00ff00ffULL) * 10 + ((columns >> 8) & 0x00ff00ff00ff00ffULL); const uint64_t quads = (pairs & 0x0000ffff0000ffffULL) * 100 + ((pairs >> 16) & 0x0000ffff0000ffffULL); value = value * 100000000 + uint(quads) * 10000 + uint(quads >> 32); p += 8; } while (unsigned(*p - '0') < 10) { value = value * 10 + unsigned(*p - '0'); ++p; } pil = uint32_t(p - ibuf); if (pil != pir) break; load(); p = ibuf; if (!pir) break; } integer_complete: pil = uint32_t(p - ibuf); if constexpr (numeric_limits::is_signed) { if (negative && value) x = T(-T(value - 1) - 1); else x = T(value); } else x = T(value); } template ::is_integer, int> = 0> __attribute__((always_inline)) inline void rd1(T &x) { rd1_integer(x); } inline void rd1(char &x) { find_token(); x = ibuf[pil++]; } inline void rd1(string &x) { find_token(); x.clear(); for (;;) { const char *p = ibuf + pil; const char *end = ibuf + pir; const char *first = p; while (p != end && !ascii_space(*p)) ++p; x.append(first, size_t(p - first)); pil = uint32_t(p - ibuf); if (p != end) return; load(); if (!pir) return; } } template void rd1_real(T &x) { string token; rd1(token); const char *first = token.data(); const char *last = first + token.size(); if (first != last && *first == '+') ++first; auto result = from_chars(first, last, x, chars_format::general); if (result.ec != errc{} || result.ptr != last) { char *end; if constexpr (is_same_v) x = strtof(token.c_str(), &end); else if constexpr (is_same_v) x = strtod(token.c_str(), &end); else x = strtold(token.c_str(), &end); if (end != token.data() + token.size()) abort(); } } inline void rd1(float &x) { rd1_real(x); } inline void rd1(double &x) { rd1_real(x); } inline void rd1(long double &x) { rd1_real(x); } template void rd1(pair &x); template void rd1(tuple &x); template void rd1(array &x); template void rd1(vc &x); template void rd1(pair &x) { rd1(x.first), rd1(x.second); } template void rd1(tuple &x) { apply([](auto &...element) { (rd1(element), ...); }, x); } template void rd1(array &x) { for (auto &element : x) rd1(element); } template void rd1(vc &x) { if constexpr (is_same_v) for (size_t i = 0; i < x.size(); ++i) { bool value; rd1(value); x[i] = value; } else for (auto &element : x) rd1(element); } inline constexpr auto decimal_triplets = [] { array, 1000> result{}; for (unsigned i = 0; i < 1000; ++i) { result[i][0] = char('0' + i / 100); result[i][1] = char('0' + i / 10 % 10); result[i][2] = char('0' + i % 10); } return result; }(); inline void store_nine(char *out, uint x) { const uint q = x / 1000, r = q / 1000; memcpy(out, decimal_triplets[r].data(), 3); memcpy(out + 3, decimal_triplets[q - r * 1000].data(), 3); memcpy(out + 6, decimal_triplets[x - q * 1000].data(), 3); } #line 2324 inline char *store_leading_triplet(char *out, uint x) { if (x >= 100) { memcpy(out, decimal_triplets[x].data(), 3); return out + 3; } if (x >= 10) { memcpy(out, decimal_triplets[x].data() + 1, 2); return out + 2; } *out = char('0' + x); return out + 1; } inline char *store_short(char *out, uint x) { if (x >= 1000000) { const uint q = x / 1000000; const uint r = x - q * 1000000; out = store_leading_triplet(out, q); memcpy(out, decimal_triplets[r / 1000].data(), 3); memcpy(out + 3, decimal_triplets[r % 1000].data(), 3); return out + 6; } if (x >= 1000) { const uint q = x / 1000; out = store_leading_triplet(out, q); memcpy(out, decimal_triplets[x - q * 1000].data(), 3); return out + 3; } return store_leading_triplet(out, x); } template inline char *store_ordinary(char *out, U x) { if constexpr (sizeof(U) > sizeof(uint)) { if (x >= 1000000000000000000ULL) { const uint hi = uint(x / 1000000000000000000ULL); const ull tail = x - ull(hi) * 1000000000000000000ULL; const uint middle = uint(tail / 1000000000ULL); out = store_leading_triplet(out, hi); store_nine(out, middle); store_nine(out + 9, uint(tail - ull(middle) * 1000000000ULL)); return out + 18; } } if (x >= 1000000000) { const uint hi = uint(x / 1000000000); out = store_short(out, hi); store_nine(out, uint(x - U(hi) * 1000000000)); return out + 9; } return store_short(out, uint(x)); } template __attribute__((always_inline)) inline void write_wide_integer(U magnitude, bool negative) ; #line 2410 template __attribute__((always_inline)) inline void wt1_integer(T x) { using U = integer_magnitude; U magnitude = U(x); bool negative = false; if constexpr (numeric_limits::is_signed) { negative = x < 0; const U sign_mask = U(0) - U(negative); magnitude = (magnitude ^ sign_mask) + U(negative); } if constexpr (sizeof(U) <= sizeof(ull)) { if (por > SIZ - 40) flush(); char *out = obuf + por; *out = '-'; out += negative; out = store_ordinary(out, magnitude); if constexpr (newline) *out++ = '\n'; por = uint32_t(out - obuf); return; } else write_wide_integer(magnitude, negative); } template ::is_integer, int> = 0> __attribute__((always_inline)) inline void wt1(T x) { wt1_integer(x); } inline void wt1(char x) { append_char(x); } inline void wt1(const char *x) { append_bytes(x, strlen(x)); } inline void wt1(string_view x) { append_bytes(x.data(), x.size()); } inline void wt1(const string &x) { append_bytes(x.data(), x.size()); } template void wt1_real(T x) { char text[numeric_limits::max_exponent10 + 64]; auto result = to_chars(text, text + sizeof(text), x, chars_format::fixed, 15); if (result.ec != errc{}) abort(); append_bytes(text, size_t(result.ptr - text)); } inline void wt1(float x) { wt1_real(x); } inline void wt1(double x) { wt1_real(x); } inline void wt1(long double x) { wt1_real(x); } template void wt1(const pair &x); template void wt1(const tuple &x); template void wt1(const array &x); template void wt1(const vc &x); template void wt1(const pair &x) { wt1(x.first), append_char(' '), wt1(x.second); } template void wt1(const tuple &x) { apply([](const auto &...element) { size_t index = 0; ((index++ ? void(append_char(' ')) : void(), wt1(element)), ...); }, x); } template void wt1(const array &x) { for (size_t i = 0; i < N; ++i) { if (i) append_char(' '); wt1(x[i]); } } template void wt1(const vc &x) { for (size_t i = 0; i < x.size(); ++i) { if (i) append_char(' '); wt1(x[i]); } } template void read(T &...x) { (rd1(x), ...); } template void write(T &&...x) { (wt1(forward(x)), ...); } template void print(T &&...x) { if constexpr (sizeof...(T) == 1 && ((is_integral_v> && !is_same_v, char>) && ...)) (wt1_integer, true>(forward(x)), ...); else { size_t index = 0; ((index++ ? void(append_char(' ')) : void(), wt1(forward(x))), ...); append_char('\n'); } } } struct Dummy { Dummy() { atexit(fastio::flush); } } dummy; //! https://trap.jp/post/1224/ #line 2556 namespace internal { template void READnodump(Ts &...a) { fastio::read(a...); } #line 2586 template void READJAGnodump(int n, vvc &...vs) { auto read_one = [&](auto &v) { v.resize(size_t(n)); for (auto &row : v) { int k; READnodump(k); row.resize(size_t(k)); READnodump(row); } }; (read_one(vs), ...); } }; #define READ(...) internal::READnodump(__VA_ARGS__); dump(__VA_ARGS__) #define LIBRARY_INOUT_TYPE(...) LIBRARY_INOUT_TYPE_IMPL(__VA_ARGS__)(__VA_ARGS__) #define LIBRARY_INOUT_TYPE_IMPL(T, ...) LIBRARY_INOUT_TYPE_SELECT(LIBRARY_INOUT_TYPE_PROBE T, LIBRARY_INOUT_TYPE_KEEP) #define LIBRARY_INOUT_TYPE_SELECT(...) LIBRARY_INOUT_TYPE_SECOND(__VA_ARGS__) #define LIBRARY_INOUT_TYPE_SECOND(_0, _1, ...) _1 #define LIBRARY_INOUT_TYPE_KEEP(...) __VA_ARGS__ #define IN(T, ...) LIBRARY_INOUT_TYPE(T) __VA_ARGS__; READ(__VA_ARGS__) #define LL(...) IN(ll, __VA_ARGS__) #define READJAG(...) internal::READJAGnodump(__VA_ARGS__); dump(__VA_ARGS__) #define JAG(T, n, ...) vvc __VA_ARGS__; READJAG(n, __VA_ARGS__) #line 2713 #define PRINT fastio::print #line 2728 template void offset(vc &v, const Add &add) { for (auto &vi : v) vi += add; } template void offset(vvc &v, const Add &add) { for (auto &vi : v) for (auto &vij : vi) vij += add; } #line 2782 namespace internal { }; #line 2819 namespace internal { }; #line 2845 mt19937_64 mt; template T randrange(U1 l, U2 r) { assert(T(l) < T(r)); return uniform_int_distribution(T(l), T(r) - 1)(mt); } #line 2877 namespace internal { #line 2912 }; #line 2941 /*! * Portions corresponding to AtCoder Library (CC0-1.0): modular arithmetic operators. * Upstream: atcoder/modint.hpp * https://github.com/atcoder/ac-library/tree/864245a00b00dd008d1abfdc239618fdb7d139da * License: https://github.com/atcoder/ac-library/blob/864245a00b00dd008d1abfdc239618fdb7d139da/LICENSE */ #line 2960 namespace larger_int_detail { template [[deprecated("larger_int: 128-bit integer is not widened; intermediate arithmetic may overflow")]] constexpr bool warn_no_wider_integer() { return true; } } 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; /*! * Portions corresponding to AtCoder Library (CC0-1.0): primality testing. * Upstream: atcoder/internal_math.hpp * https://github.com/atcoder/ac-library/tree/864245a00b00dd008d1abfdc239618fdb7d139da * License: https://github.com/atcoder/ac-library/blob/864245a00b00dd008d1abfdc239618fdb7d139da/LICENSE */ 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_constexpr(T n) { if constexpr (sizeof(T) > 4) { if (n <= INT_MAX) return isprime_constexpr(n); } if (n <= 1) return false; if (n == 2 || n == 7 || n == 61) return true; if (n % 2 == 0) return false; ll d = n - 1; while (d % 2 == 0) d /= 2; using U = make_unsigned_t; using L = larger_int_t; auto miller_rabin = [&](const auto &bases) constexpr { for (ll a : bases) { ll t = d, y = powmod_constexpr(a, t, n); while (t != n - 1 && y != 1 && y != n - 1) { y = L(y) * y % n; t <<= 1; } if (y != n - 1 && t % 2 == 0) return false; } return true; }; if constexpr(sizeof(T) <= 4) { constexpr ll bases[3] = {2, 7, 61}; return miller_rabin(bases); } else { constexpr ll bases[7] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022}; return miller_rabin(bases); } } 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 mod_type mod() { return M; } static constexpr value_type umod() { return M; } static constexpr value_type init(value_type v) { return v; } static constexpr mod_type val(value_type v) { return v; } static constexpr value_type mul(value_type a, value_type b) { const calc_type product = calc_type(a) * b; if constexpr (M == (1LL << 61) - 1) { const value_type reduced = (value_type(product) & umod()) + value_type(product >> 61); return reduced >= umod() ? reduced - umod() : reduced; } else return value_type(product % M); } }; }; /*! * Portions corresponding to AtCoder Library (CC0-1.0): Barrett reduction. * Upstream: atcoder/internal_math.hpp * https://github.com/atcoder/ac-library/tree/864245a00b00dd008d1abfdc239618fdb7d139da * License: https://github.com/atcoder/ac-library/blob/864245a00b00dd008d1abfdc239618fdb7d139da/LICENSE */ 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 mod_type mod() { return reducer.umod(); } static value_type umod() { return reducer.umod(); } static value_type init(value_type v) { return v; } static mod_type val(value_type v) { return v; } static value_type mul(value_type a, value_type b) { return reducer.mul(a, b); } }; }; 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); } }; //! https://www.mathenachia.blog/even-mod-montgomery-impl/ 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 mod_type mod() { return reducer.umod(); } static value_type umod() { return reducer.umod(); } static value_type init(value_type v) { return reducer.inv_reduce(v); } static mod_type val(value_type v) { return reducer.reduce(v); } static value_type mul(value_type a, value_type b) { return reducer.reduce((calc_type)a * b); } }; 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 mod_type mod() { return reducer.umod(); } static value_type umod() { return reducer.umod(); } static value_type init(value_type v) { return reducer.inv_reduce(v); } static mod_type val(value_type v) { return reducer.reduce(v); } static value_type mul(value_type a, value_type b) { return reducer.reduce((calc_type)a * b); } }; }; #include #include #include namespace internal { template inline constexpr bool is_modint_decimal_input = std::is_convertible_v && !std::is_same_v, decltype(nullptr)>; template bool parse_modint_decimal(std::string_view s, [[maybe_unused]] bool allow_negative, F &&read_digit) { assert(!s.empty() && "modint: decimal input requires at least one digit"); const bool negative = s.front() == '-'; if (s.front() == '+' || negative) s.remove_prefix(1); assert(!s.empty() && "modint: decimal input requires at least one digit"); assert((allow_negative || !negative) && "modint: negative decimal input is not allowed"); for (char c : s) { assert('0' <= c && c <= '9' && "modint: invalid decimal digit"); read_digit(c - '0'); } return negative; } } template constexpr tuple extgcd(T a, T b) ; #line 3365 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: static constexpr M mod() { M m = Policy::mod(); assert(m > 0 && "modint: modulus is not set; call mint::set_mod(m) before use"); return m; } static mint raw(V v) { mint x; x._v = v; return x; } modint_impl() : _v(0) { (void)mod(); } template >> modint_impl(T v) { const V m = mod(); V rem; if constexpr (is_signed_ext) { using S = make_signed_t; S x = v % S(m); if (x < 0) x += m; rem = x; } else rem = V(v % m); _v = Policy::init(rem); }; template , int> = 0> explicit modint_impl(const S &s) : modint_impl() { const mint ten = 10; const bool negative = parse_modint_decimal(string_view(s), true, [&](int digit) { *this *= ten; *this += digit; }); if (negative) *this = -*this; } M val() const { return Policy::val(_v); } mint &operator+=(const mint &rhs) { _v += rhs._v; if (_v >= Policy::umod()) _v -= Policy::umod(); return *this; } mint &operator-=(const mint &rhs) { _v -= rhs._v; if (_v >= Policy::umod()) _v += Policy::umod(); return *this; } mint &operator*=(const mint &rhs) { _v = Policy::mul(_v, rhs._v); return *this; } mint &operator/=(const mint &rhs) { if constexpr (is_void_v) assert(rhs._v != 0 && "modint: division by zero"); return *this *= rhs.inv(); } mint &operator++() { _v++; if (_v == Policy::umod()) _v = 0; return *this; } mint &operator--() { if (_v == 0) _v = Policy::umod(); _v--; return *this; } mint operator++(int) { mint res = *this; ++(*this); return res; } mint operator--(int) { mint res = *this; --(*this); return res; } mint operator+() const { return *this; } mint operator-() const { return mint() - *this; } template mint pow(T n) const { assert(n >= 0); if constexpr (!is_void_v) return raw(PowInv::get().pow(val(), n)); mint x = *this, r = 1; while (n) { if (n & 1) r *= x; x *= x; n >>= 1; } return r; } mint inv() const { if constexpr (!is_void_v) { return raw(PowInv::get().inv(val())); } else if constexpr (Policy::is_prime) { return pow(mod() - 2); } else { auto [g, x, y] = extgcd(val(), mod()); assert(g == 1); return mint(x); } } 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(); } #line 3548 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 static_modint64 = internal::modint_impl>; template using dynamic_modint64_odd = internal::modint_impl>; template using dynamic_modint64 = internal::modint_impl>; using modint998244353 = static_modint32<998244353>; using modint1000000007 = static_modint32<1000000007>; using modint = dynamic_modint32<-1>; using modint61 = static_modint64<(1LL << 61) - 1>; using modint64 = dynamic_modint64<-1>; 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; template struct has_mod : std::false_type { }; template struct has_mod> : std::true_type { }; template struct modint_less { bool operator()(const mint &a, const mint &b) const { if constexpr (is_modint_v) return a.val() < b.val(); else return a < b; } }; template struct modint_hash { auto operator()(const mint &x) const { if constexpr (is_modint_v) return std::hash{}(x.val()); else return std::hash{}(x); } }; template struct PowerTable { private: decltype(mint::mod()) mod{}; mint base{}; vc pw; public: CPP_DUMP_DEFINE_DATA(mod, base, pw); PowerTable() {} PowerTable(const mint &base) : mod(mint::mod()), base(base), pw(1, 1) {} void reserve(int n) { if (mod != mint::mod()) { mod = mint::mod(); pw = {1}; } int i = pw.size(); if (n < i) return; pw.resize(n + 1); for (; i <= n; i++) pw[i] = pw[i - 1] * base; } mint pow(int n) { assert(n >= 0); reserve(n); return pw[n]; } }; template struct Binomial { private: inline static decltype(T::mod()) mod; public: inline static vc fac_, finv_, inv_; static void reserve(int n) { if constexpr (is_dynamic_modint_v) { if (mod != T::mod()) { mod = T::mod(); fac_ = {1, 1}, finv_ = {1, 1}, inv_ = {0, 1}; } } else { if (fac_.empty()) fac_ = {1, 1}, finv_ = {1, 1}, inv_ = {0, 1}; } if (n < SZ(fac_)) return; chmin(n, T::mod() - 1); int si = fac_.size(); fac_.resize(n + 1), finv_.resize(n + 1), inv_.resize(n + 1); repi(i, si, n + 1) { fac_[i] = fac_[i - 1] * T::raw(i); inv_[i] = -inv_[T::mod() % i] * T::raw(T::mod() / i); finv_[i] = finv_[i - 1] * inv_[i]; } } #line 3749 static T inv(int n) { n %= T::mod(); if (n < 0) n += T::mod(); assert(n != 0); reserve(n); return inv_[n]; } static T P(int n, int k) ; static T C(int n, int k) ; #line 3787 }; #line 3808 template > pair svp2d(const pair &a, const pair &b) ; #line 3846 template pair mint_to_rat(const mint &x) { auto [p, q] = svp2d({x.val(), 1}, {mint::mod(), 0}); if (q < 0) p = -p, q = -q; return {p, q}; } 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; } }; struct mint_to_rat_fn { template requires requires(const T &x) { { T::mod() } -> std::convertible_to; { x.val() } -> std::convertible_to; } constexpr auto operator()(const T &x) const -> rat_value { auto [p, q] = mint_to_rat(x); return {p, q}; } }; template struct rat_object { T value; }; 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 { template static constexpr bool can_convert() ; #line 3948 template requires(!requires { std::views::all | std::declval(); }) constexpr decltype(auto) operator()(T &&t) const { if constexpr (!std::ranges::range && std::invocable) { return mint_to_rat_fn{}(std::forward(t)); } else if constexpr (can_convert()) { if constexpr (!std::ranges::range || rat_is_map>) return rat_object{std::forward(t)}; else return std::forward(t) | std::views::transform(*this); } else { return std::forward(t); } } }; #line 4022 template requires(!requires { std::views::all | std::declval(); }) constexpr decltype(auto) operator|(T &&t, rat_closure c) { return c(std::forward(t)); } } using mint = modint998244353; // using mint = modint1000000007; // using mint = static_modint<1000000000>; // using mint = modint; using bi = Binomial; void init() { oj(mt.seed(random_device()())); } #line 4064 namespace internal_monoid_power { template struct HasMemberScalarProduct : false_type {}; template struct HasMemberScalarProduct().operator*({declval()})))>> : true_type {}; template struct HasFreeScalarProduct : false_type {}; template struct HasFreeScalarProduct(), {declval()})))>> : true_type {}; template struct HasScalarProduct : bool_constant || is_same_v || HasMemberScalarProduct::value || HasFreeScalarProduct::value> {}; template constexpr T scale(const T &x, I k) ; #line 4138 template using ConstRefPower = typename M::S (*)(const typename M::S &, I); template using ValuePower = typename M::S (*)(typename M::S, I); template struct HasConstRefPower : false_type {}; template struct HasConstRefPower>(M::pow))>> : true_type {}; template struct HasValuePower : false_type {}; template struct HasValuePower>(M::pow))>> : true_type {}; template constexpr typename M::S power(const typename M::S &x, I k) ; } template struct Monoid { using S = S_; static constexpr auto op = op_; static constexpr auto e = e_; }; template struct Group { using S = S_; static constexpr auto op = op_; static constexpr auto e = e_; static constexpr auto inv = inv_; }; template struct SemiRing { using S = S_; static constexpr auto add = add_; static constexpr auto e0 = e0_; static constexpr auto mul = mul_; static constexpr auto e1 = e1_; }; template struct Ring { using S = S_; static constexpr auto add = add_; static constexpr auto e0 = e0_; static constexpr auto minus = minus_; static constexpr auto mul = mul_; static constexpr auto e1 = e1_; }; template struct Field { using S = S_; static constexpr auto add = add_; static constexpr auto e0 = e0_; static constexpr auto minus = minus_; static constexpr auto mul = mul_; static constexpr auto e1 = e1_; static constexpr auto inv = inv_; }; template struct HasInverse : false_type {}; template struct HasInverse()))>> : true_type {}; template struct OppositeMonoid { using S = typename M::S; static constexpr S op(const S &a, const S &b) { return M::op(b, a); } static constexpr auto e = M::e; template static constexpr S pow(const S &x, I k) { return internal_monoid_power::power(x, k); } }; template struct OppositeGroup { using S = typename G::S; static constexpr S op(const S &a, const S &b) { return G::op(b, a); } static constexpr auto e = G::e; static constexpr auto inv = G::inv; template static constexpr S pow(const S &x, I k) { return internal_monoid_power::power(x, k); } }; template struct NormalAndOppositeMonoid { struct S { typename M::S normal; typename M::S opposite; S() {} template , std::nullptr_t> = nullptr> S(Args &&...args) : normal(std::forward(args)...), opposite(normal) {} S(const typename M::S &normal, const typename M::S &opposite) : normal(normal), opposite(opposite) {} }; static constexpr S op(const S &a, const S &b) { return {M::op(a.normal, b.normal), M::op(b.opposite, a.opposite)}; } static constexpr S e() { return {M::e(), M::e()}; } template static constexpr S pow(const S &x, I k) { return {internal_monoid_power::power(x.normal, k), internal_monoid_power::power(x.opposite, k)}; } }; template struct NormalAndOppositeGroup { struct S { typename G::S normal; typename G::S opposite; S() {} template , std::nullptr_t> = nullptr> S(Args &&...args) : normal(std::forward(args)...), opposite(normal) {} S(const typename G::S &normal, const typename G::S &opposite) : normal(normal), opposite(opposite) {} }; static constexpr S op(const S &a, const S &b) { return {G::op(a.normal, b.normal), G::op(b.opposite, a.opposite)}; } static constexpr S e() { return {G::e(), G::e()}; } static constexpr S inv(const S &a) { return {G::inv(a.normal), G::inv(a.opposite)}; } template static constexpr S pow(const S &x, I k) { return {internal_monoid_power::power(x.normal, k), internal_monoid_power::power(x.opposite, k)}; } }; template using MonoidOfSemiRingAdd = Monoid; template using MonoidOfSemiRingMul = Monoid; template using GroupOfRingAdd = Group; template using GroupOfFieldMul = Group; template struct SemiRingFromMonoidMonoid { static_assert(is_same_v, "Madd::S and Mmul::S must be identical"); using S = typename Madd::S; static constexpr auto add = Madd::op; static constexpr auto e0 = Madd::e; static constexpr auto mul = Mmul::op; static constexpr auto e1 = Mmul::e; }; template struct RingFromGroupMonoid { static_assert(is_same_v, "Gadd::S and Mmul::S must be identical"); using S = typename Gadd::S; static constexpr auto add = Gadd::op; static constexpr auto e0 = Gadd::e; static constexpr auto minus = Gadd::inv; static constexpr auto mul = Mmul::op; static constexpr auto e1 = Mmul::e; }; template struct FieldFromGroupGroup { static_assert(is_same_v, "Gadd::S and Gmul::S must be identical"); using S = typename Gadd::S; static constexpr auto add = Gadd::op; static constexpr auto e0 = Gadd::e; static constexpr auto minus = Gadd::inv; static constexpr auto mul = Gmul::op; static constexpr auto e1 = Gmul::e; static constexpr auto inv = Gmul::inv; }; template struct has_e1 : false_type {}; template struct has_e1> : true_type {}; template inline constexpr bool has_e1_v = has_e1::value; template struct MonoidMul { using S = T; static constexpr S op(S a, S b) { return a * b; } static constexpr S e() { if constexpr (has_e1_v) return S::e1(); else return S(1); } }; template struct GroupAddSub { 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 S{}; } static constexpr S inv(S a) { return -a; } template () * declval())> static constexpr S pow(const S &a, I k) { return a * k; } }; template struct GroupMulDiv { using S = T; static constexpr S op(S a, S b) { return a * b; } static constexpr S e() { if constexpr (has_e1_v) return S::e1(); else return S(1); } static constexpr S inv(S a) { return e() / a; } }; template using SemiRingMinPlus = SemiRingFromMonoidMonoid, MonoidAdd>; template using SemiRingMaxPlus = SemiRingFromMonoidMonoid, MonoidAdd>; template using RingAddSubMul = RingFromGroupMonoid, MonoidMul>; template using FieldAddSubMulDiv = FieldFromGroupGroup, GroupMulDiv>; #line 4415 namespace internal { template struct ordinary_mod32 : false_type {}; template struct ordinary_mod32, PowInv>> : true_type {}; template struct ordinary_mod32> : true_type {}; } namespace internal { template struct ordinary_mod32_add_group : false_type {}; template struct ordinary_mod32_add_group> : ordinary_mod32 {}; template struct ordinary_mod32_add_group::op, GroupAddSub::e, GroupAddSub::inv>> : ordinary_mod32 {}; template struct ordinary_mod32_field : false_type {}; template struct ordinary_mod32_field> : ordinary_mod32 {}; } #include #include #include namespace internal { template inline std::uint32_t block_dot32(std::size_t n, std::uint32_t mod, std::size_t block, std::uint32_t seed, NextProduct next) { std::uint64_t carry = seed; while (n) { const std::size_t count = std::min(n, block); std::size_t i = 0; std::uint64_t s0 = carry, s1 = 0, s2 = 0, s3 = 0; for (; i + 4 <= count; i += 4) { s0 += next(); s1 += next(); s2 += next(); s3 += next(); } for (; i < count; ++i) s0 += next(); carry = (s0 + s1 + s2 + s3) % mod; n -= count; } return static_cast(carry); } } namespace internal { template using dot_product_mod32_value = ordinary_mod32; template S dot_product_mod32_impl(int n, It1 a, It2 b) { return S::raw(block_dot32(n, S::mod(), block, 0, [&]() { return ull((a++)->val()) * (b++)->val(); })); } template S dot_product_mod32_values(int n, It1 a, It2 b) { static_assert(ordinary_mod32::value); assert(n >= 0); if (S::mod() <= (1 << 30)) return dot_product_mod32_impl<16, S>(n, a, b); return dot_product_mod32_impl<4, S>(n, a, b); } } namespace internal { template struct dot_product_mod32 : false_type {}; template struct dot_product_mod32> : dot_product_mod32_value {}; template struct dot_product_mod32> : dot_product_mod32_value {}; template struct dot_product_mod32, MonoidMul>> : dot_product_mod32_value {}; } template typename SR::S dot_product(int n, It1 a, It2 b) { using S = typename SR::S; assert(n >= 0); if constexpr (internal::dot_product_mod32::value) { return internal::dot_product_mod32_values(n, a, b); } else { S sum = SR::e0(); repi(i, n) sum = SR::add(sum, SR::mul(*a++, *b++)); return sum; } } //! https://codeforces.com/blog/entry/61306 template struct BerlekampMassey { using S = typename F::S; vc a, b, c, tmp; int pos = -1; S inv_x = F::e0(); CPP_DUMP_DEFINE_DATA(a, c, pos); int degree() const ; void append(S value) { const int i = a.size(), d = c.size(); a.eb(value); S y = F::add(value, F::minus(dot_product(d, c.begin(), a.rbegin() + 1))); if (y == F::e0()) return; if (c.empty()) { c.assign(i + 1, F::e0()); pos = i; inv_x = F::inv(y); return; } S z = F::mul(y, inv_x); int d2 = i - pos + b.size(); if (d2 > d) { tmp = c; c.resize(d2, F::e0()); } c[i - 1 - pos] = F::add(c[i - 1 - pos], z); const S minus_z = F::minus(z); repi(j, b.size()) c[i - pos + j] = F::add(c[i - pos + j], F::mul(minus_z, b[j])); if (d2 > d) pos = i, inv_x = F::inv(y), swap(tmp, b); } vc coefficients() const { vc res; res.reserve(c.size() + 1); res.eb(F::minus(F::e1())); res.insert(res.end(), c.begin(), c.end()); return res; } }; template vc berlekamp_massey(const vc &a) { BerlekampMassey bm; bm.a.reserve(a.size()); for (const auto &x : a) bm.append(x); return bm.coefficients(); } template mint random_modint() { return mint(randrange(nonzero ? 1 : 0, mint::mod())); } //! https://yukicoder.me/wiki/black_box_linear_algebra namespace bbla { template mint random_sample_mint() ; template vc krylov_sequence(const LinearMap &linear_map, const vc &u, vc v, int count) { using S = typename F::S; assert(count >= 0 && u.size() == v.size()); vc a(count, F::e0()); repi(i, count) { a[i] = dot_product(u.size(), u.begin(), v.begin()); if (i + 1 < count) linear_map(v); } return a; } #line 4703 template )> vc minimal_polynomial(int n, const LinearMap &linear_map, const RandomSample &random_sample = random_sample_mint) { using S = typename F::S; assert(n >= 0); vc u(n, F::e0()), v(n, F::e0()); repi(j, n) u[j] = random_sample(), v[j] = random_sample(); return reversed(berlekamp_massey(krylov_sequence(linear_map, u, move(v), 2 * n))); } #line 4792 } template struct CSR { protected: int n, m; vc start; vc elist; vc len; inline int get_last(int i) const { if constexpr (is_erasable) return start[i] + len[i]; else return start[i + 1]; } template struct RowBase { using iterator = Iter; using reference = typename iterator_traits::reference; private: iterator begi, endi; public: RowBase(const iterator &begi, const iterator &endi) : begi(begi), endi(endi) {} inline iterator begin() const { return begi; } inline iterator end() const { return endi; } template inline I size() const { return endi - begi; } inline bool empty() const { return size() == 0; } inline reference operator[](int i) const { return *(begi + i); } inline reference front() const { assert(!empty()); return *begi; } inline reference back() const { assert(!empty()); return *prev(endi); } vc content() const ; }; using Row = RowBase::iterator>; using ConstRow = RowBase::const_iterator>; public: CSR() : n(0), m(0), start{0} {} template CSR(const vc &row_sizes) : n(row_sizes.size()) { static_assert(is_integral_ext); start.resize(n + 1); for (int i = 0; i < n; i++) { if constexpr (is_signed_ext) assert(row_sizes[i] >= 0); start[i + 1] = start[i] + int(row_sizes[i]); } m = start.back(); elist.resize(m); if constexpr (is_erasable) len.assign(ALL(row_sizes)); } template CSR(int n, const vc> &ies) : n(n), m(ies.size()), start(n, 0), elist(m) { if constexpr (is_erasable) len.resize(n); fec([ i, e ] : ies) { assert(0 <= i && i < n); start[i]++; } start = cumlsum(start); if constexpr (is_erasable) repi(i, n) len[i] = start[i + 1] - start[i]; auto cnt = start; repi(j, m) { cauto & [ i, e ] = ies[j]; int &k = cnt[i]; elist[k] = e; k++; } } template CSR(const vvc &vv) : n(vv.size()), start(n + 1, 0) { m = 0; fec(row : vv) m += row.size(); elist.resize(m); if constexpr (is_erasable) len.resize(n); for (int i = 0, j = 0; i < n; i++) { start[i] = j; if constexpr (is_erasable) len[i] = vv[i].size(); fec(e : vv[i]) { elist[j] = e; j++; } } start.back() = m; } template explicit CSR(const CSR &other) : CSR(gen_vec(other.template size(), [&](int i) { return other[i].template size(); })) { for (int i = 0; i < n; i++) copy(ALL(other[i]), elist.begin() + start[i]); } Row operator[](int i) { return Row(elist.begin() + start[i], elist.begin() + get_last(i)); } ConstRow operator[](int i) const { return ConstRow(elist.begin() + start[i], elist.begin() + get_last(i)); } #line 4957 int offset(int i) const { assert(0 <= i && i <= n); return start[i]; } #line 4986 template I size() const { return n; } vvc content() const ; vc &get_elist() { return elist; } const vc &get_elist() const { return elist; } }; template CSR(const vvc &) -> CSR; namespace internal { template pair row_reduction_mod32(Rows &a, int n, int m, bool rref) { if (n == 0 || m == 0) return {0, S(1)}; if (none_of(a.begin(), a.end(), [](const auto &row) { return any_of(row.begin(), row.end(), [](S x) { return x.val() != 0; }); })) return {0, S(0)}; const ull mod = S::mod(); const int block = mod <= (1u << 30) ? 16 : 4; vvc w(n, vc(m)); vc used(n); vc first(n); repi(i, n) repi(j, m) w[i][j] = a[i][j].val(); int rk = 0; S de = 1; for (int i = 0, j = 0; i < n && j < m; ++j) { int k = i, next = m; for (; k < n; ++k) { while (first[k] < m && (w[k][first[k]] %= mod) == 0) ++first[k]; if (first[k] == j) break; next = min(next, first[k]); } if (k == n) { de = 0; if (next == m) break; j = next - 1; continue; } if (k != i) { swap(w[k], w[i]); swap(used[k], used[i]); swap(first[k], first[i]); de = -de; } S pivot = S::raw(w[i][j]); de *= pivot; S inv = pivot.inv(); repi(l, j, m) w[i][l] = (S::raw(w[i][l] % mod) * inv).val(); used[i] = 0; repi(k, rref ? 0 : i + 1, n) if (k != i) { if (first[k] > j) continue; ull c = w[k][j] % mod; w[k][j] = 0; if (k > i) first[k] = j + 1; if (c == 0) continue; if (used[k] == block) { repi(l, j + 1, m) w[k][l] %= mod; used[k] = 0; } c = mod - c; repi(l, j + 1, m) w[k][l] += c * w[i][l]; ++used[k]; } ++i; ++rk; } repi(i, n) repi(j, m) a[i][j] = S::raw(first[i] == m ? 0 : w[i][j] % mod); return {rk, de}; } } #include #include #include #include #include #include #include namespace internal { namespace matrix_power_mod32_detail { template inline constexpr bool supported_builtin_exponent_v = std::is_integral_v || std::is_same_v || std::is_same_v ; template using Matrix = std::vector>; #line 5145 template std::size_t binary_multiplication_count(T exponent) ; #line 5436 template Matrix power_over_field(const Matrix& a, T exponent) ; #line 5495 template bool is_prime_modulus() ; #line 5510 } } namespace internal { template struct matrix_row { using value_type = typename iterator_traits::value_type; using reference = typename iterator_traits::reference; Iterator first, last; Iterator begin() const { return first; } Iterator end() const { return last; } size_t size() const { return last - first; } bool empty() const { return first == last; } reference operator[](size_t j) const { return first[j]; } reference front() const { return *first; } reference back() const { return *prev(last); } operator vc() const { return {first, last}; } matrix_row &operator=(const matrix_row &b) { assert(size() == b.size()); if (first != b.first) copy(b.begin(), b.end(), first); return *this; } template matrix_row &operator=(const Range &b) { assert(size() == b.size()); copy(b.begin(), b.end(), first); return *this; } matrix_row &operator=(initializer_list b) { assert(size() == b.size()); copy(b.begin(), b.end(), first); return *this; } template bool operator==(const Range &b) const { return size() == b.size() && equal(first, last, b.begin()); } template bool operator!=(const Range &b) const { return !(*this == b); } }; template bool operator==(const vector &a, const matrix_row &b) { return b == a; } template bool operator==(const array &a, const matrix_row &b) { return b == a; } template struct matrix_row_iterator { using value_type = decltype(declval()[0]); using reference = value_type; using pointer = void; using difference_type = ptrdiff_t; using iterator_category = random_access_iterator_tag; Owner *owner = nullptr; difference_type index = 0; reference operator*() const { return (*owner)[index]; } reference operator[](difference_type k) const { return (*owner)[index + k]; } matrix_row_iterator &operator++() { ++index; return *this; } matrix_row_iterator operator++(int) { auto old = *this; ++*this; return old; } matrix_row_iterator &operator--() { --index; return *this; } matrix_row_iterator operator--(int) { auto old = *this; --*this; return old; } matrix_row_iterator &operator+=(difference_type k) { index += k; return *this; } matrix_row_iterator &operator-=(difference_type k) { index -= k; return *this; } friend matrix_row_iterator operator+(matrix_row_iterator a, difference_type k) { return a += k; } friend matrix_row_iterator operator+(difference_type k, matrix_row_iterator a) { return a += k; } friend matrix_row_iterator operator-(matrix_row_iterator a, difference_type k) { return a -= k; } friend difference_type operator-(matrix_row_iterator a, matrix_row_iterator b) { return a.index - b.index; } friend bool operator==(matrix_row_iterator a, matrix_row_iterator b) { return a.owner == b.owner && a.index == b.index; } friend bool operator!=(matrix_row_iterator a, matrix_row_iterator b) { return !(a == b); } friend bool operator<(matrix_row_iterator a, matrix_row_iterator b) { return a.index < b.index; } friend bool operator>(matrix_row_iterator a, matrix_row_iterator b) { return b < a; } friend bool operator<=(matrix_row_iterator a, matrix_row_iterator b) { return !(b < a); } friend bool operator>=(matrix_row_iterator a, matrix_row_iterator b) { return !(a < b); } }; template struct matrix_storage { using reference = typename vc::reference; using const_reference = typename vc::const_reference; private: int rows_ = 0, columns_ = 0; vc values_; public: matrix_storage() = default; matrix_storage(int n, int m, const T &value) : rows_(n), columns_(m), values_(size_t(n) * m, value) { assert(n >= 0 && m >= 0); } matrix_storage(const vvc &a) : rows_(a.size()), columns_(a.empty() ? 0 : a[0].size()) { values_.reserve(size_t(rows_) * columns_); for (const auto &r : a) { assert(SZ(r) == columns_); values_.insert(values_.end(), r.begin(), r.end()); } } matrix_storage(const matrix_storage &) = default; matrix_storage &operator=(const matrix_storage &) = default; matrix_storage(matrix_storage &&a) noexcept : rows_(exchange(a.rows_, 0)), columns_(exchange(a.columns_, 0)), values_(move(a.values_)) { } matrix_storage &operator=(matrix_storage &&a) noexcept { if (this != &a) { rows_ = exchange(a.rows_, 0); columns_ = exchange(a.columns_, 0); values_ = move(a.values_); } return *this; } size_t size() const { return rows_; } bool empty() const { return rows_ == 0; } template pair shape() const { return {I(rows_), I(columns_)}; } reference operator()(int i, int j) { return values_[size_t(i) * columns_ + j]; } const_reference operator()(int i, int j) const { return values_[size_t(i) * columns_ + j]; } auto row(int i) { auto b = values_.begin() + size_t(i) * columns_; return matrix_row{b, b + columns_}; } auto row(int i) const { auto b = values_.begin() + size_t(i) * columns_; return matrix_row{b, b + columns_}; } auto operator[](int i) { return row(i); } auto operator[](int i) const { return row(i); } auto front() { return row(0); } auto front() const { return row(0); } auto back() { return row(rows_ - 1); } auto back() const { return row(rows_ - 1); } auto begin() { return matrix_row_iterator{this, 0}; } auto end() { return matrix_row_iterator{this, rows_}; } auto begin() const { return matrix_row_iterator{this, 0}; } auto end() const { return matrix_row_iterator{this, rows_}; } void swap_rows(int i, int j) { if (i != j) swap_ranges(row(i).begin(), row(i).end(), row(j).begin()); } const vc &content() const ; template vvc to_vvi() const ; operator vvc() const { return to_vvi(); } friend bool operator==(const matrix_storage &a, const matrix_storage &b) { return a.shape() == b.shape() && a.values_ == b.values_; } friend bool operator!=(const matrix_storage &a, const matrix_storage &b) { return !(a == b); } }; } namespace internal { template void matrix_product(int n, int m, int p, const A &a, const B &b, C &c) ; #line 5855 } template struct Matrix : internal::matrix_storage { using S = typename F::S; using M = Matrix; using V = vc; using Base = internal::matrix_storage; template pair shape() const { return Base::template shape(); } Matrix() = default; Matrix(int n, int m, const S &diag = F::e0(), const S &non_diag = F::e0()) : Base(n, m, non_diag) { repi(i, min(n, m)) (*this)(i, i) = diag; } Matrix(const vvc &a) : Base(a) {} Matrix(initializer_list a) : Matrix(vvc(a)) {} M transpose() const { auto [n, m] = shape(); M result(m, n); constexpr int block = 32; for (int j = 0; j < m; j += block) for (int i = 0; i < n; i += block) for (int r = i; r < min(i + block, n); ++r) for (int c = j; c < min(j + block, m); ++c) result[c][r] = (*this)[r][c]; return result; } V column(int j) const { auto [n, m] = shape(); assert(0 <= j && j < m); return gen_vec(n, [&](int i) -> S { return (*this)[i][j]; }); } template M select_rows(const vc &indices) const { static_assert(is_integral_ext); auto [n, m] = shape(); M result(indices.size(), m); for (int i = 0; i < int(indices.size()); ++i) { assert(u128(indices[i]) < unsigned(n)); result[i] = (*this)[int(indices[i])]; } return result; } #line 5930 M &scale_rows(const V &scale) ; #line 5949 M operator-() const { auto [n, m] = shape(); M res(*this); repi(i, n) repi(j, m) res[i][j] = F::minus(res[i][j]); return res; } M &operator+=(const M &b) { assert(shape() == b.shape()); auto [n, m] = shape(); repi(i, n) repi(j, m) (*this)[i][j] = F::add((*this)[i][j], b[i][j]); return *this; } M &operator-=(const M &b) { assert(shape() == b.shape()); auto [n, m] = shape(); repi(i, n) repi(j, m) (*this)[i][j] = F::add((*this)[i][j], F::minus(b[i][j])); return *this; } M &operator*=(const S &x) { auto [n, m] = shape(); repi(i, n) repi(j, m) (*this)[i][j] = F::mul((*this)[i][j], x); return *this; } M &operator/=(const S &x) { return *this *= F::inv(x); } V operator*(const V &v) const { auto [n, m] = shape(); assert(SZ(v) == m); V res(n, F::e0()); repi(i, n) res[i] = dot_product(m, (*this)[i].begin(), v.begin()); return res; } friend V operator*(const V &v, const M &a) { auto [n, m] = a.template shape(); assert(SZ(v) == n); V res(m, F::e0()); repi(i, n) repi(j, m) res[j] = F::add(res[j], F::mul(v[i], a[i][j])); return res; } M operator*(const M &b) const { auto [n, m] = shape(); auto [m_, p] = b.shape(); assert(m == m_); M res(n, p); internal::matrix_product(n, m, p, *this, b, res); return res; } template M pow(T k) const { auto [n, m] = shape(); assert(n == m); if (n == 0) return M(n, n, F::e1()); if constexpr (internal::ordinary_mod32_field::value && internal::matrix_power_mod32_detail::supported_builtin_exponent_v) { if (n >= 24 && k > 0 && internal::matrix_power_mod32_detail::binary_multiplication_count(k) > 10 && internal::matrix_power_mod32_detail::is_prime_modulus()) { const vvc &a = *this; return M(internal::matrix_power_mod32_detail::power_over_field(a, k)); } } M res(n, n, F::e1()), tmp(*this); while (k > 0) { if (k & 1) res *= tmp; tmp *= tmp; k >>= 1; } return res; } M operator+(const M &a) const { return M(*this) += a; } M operator-(const M &a) const { return M(*this) -= a; } M operator*(const S &x) const { return M(*this) *= x; } M operator/(const S &x) const { return M(*this) /= x; } M &operator*=(const M &a) { return *this = *this * a; } template tuple row_reduction(bool rref = false) const { auto [n, m] = shape(); M a(*this); if constexpr (internal::ordinary_mod32_field::value) { if (n >= 32 && m >= 32) { auto [rk, de] = internal::row_reduction_mod32(a, n, m, rref); return {std::move(a), I(rk), de}; } } I rk = 0; S de = F::e1(); for (int i = 0, j = 0; i < n && j < m; j++) { repi(k, i, n) { if (a[k][j] != F::e0()) { a.swap_rows(k, i); if (k != i) de = F::minus(de); break; } } if (a[i][j] == F::e0()) { de = F::e0(); continue; } de = F::mul(de, a[i][j]); S aij_inv = F::inv(a[i][j]); repi(l, j + 1, m) a[i][l] = F::mul(a[i][l], aij_inv); a[i][j] = F::e1(); if (rref) { repi(k, i) { S akj = a[k][j]; if (akj == F::e0()) continue; a[k][j] = F::e0(); repi(l, j + 1, m) a[k][l] = F::add(a[k][l], F::minus(F::mul(a[i][l], akj))); } } repi(k, i + 1, n) { S akj = a[k][j]; if (akj == F::e0()) continue; a[k][j] = F::e0(); repi(l, j + 1, m) a[k][l] = F::add(a[k][l], F::minus(F::mul(a[i][l], akj))); } i++; rk++; } return {a, rk, de}; } template I rank() const { return get<1>(row_reduction()); } #line 6174 optional inv() const { auto [n, m] = shape(); assert(n == m); M a(n, 2 * n); repi(i, n) repi(j, n) a[i][j] = (*this)[i][j]; repi(i, n) a[i][n + i] = F::e1(); M b = get<0>(a.row_reduction(true)); repi(i, n) if (b[i][i] == F::e0()) return nullopt; M res(n, n); repi(i, n) repi(j, n) res[i][j] = b[i][n + j]; return res; } #line 6221 }; namespace internal { template struct BasisTag { using Type = Tag; Tag tag; explicit BasisTag(Tag tag) : tag(std::move(tag)) {} bool accepts(const Tag *threshold) const { return !threshold || !(tag < *threshold); } }; template <> struct BasisTag { using Type = monostate; explicit BasisTag(monostate = {}) {} bool accepts(const monostate *) const { return true; } }; } template class LinearBasis { template friend class LinearBasis; using TagData = internal::BasisTag; using StoredTag = typename TagData::Type; static constexpr bool tagged = !is_void_v; public: using S = typename F::S; using TagType = Tag; private: using Coefficient = conditional_t, monostate>; struct Row : TagData { int pivot; vc value; Coefficient coefficient; #line 6285 Row(int pivot, vc value, Coefficient coefficient, StoredTag tag) : TagData(std::move(tag)), pivot(pivot), value(std::move(value)), coefficient(std::move(coefficient)) {} }; int dimension_; bool use_tags_ = false; vc rows_; vvc original_; static void scale(vc &value, const S &factor) ; vc eliminate(vc value, vc *coefficient, const StoredTag *threshold) const ; #line 6328 template bool insert_impl(const vc &value, StoredTag tag) ; #line 6381 public: explicit LinearBasis(int dimension = 0) : dimension_(dimension) { assert(dimension >= 0); } LinearBasis(int dimension, const vvc &vectors) : LinearBasis(dimension) { for (const auto &value : vectors) insert(value); } CPP_DUMP_DEFINE_DATA(dimension_, use_tags_, rows_, original_); int dimension() const ; int rank() const { return int(rows_.size()); } void clear() { rows_.clear(), original_.clear(), use_tags_ = false; } bool insert(const vc &value) { if constexpr (tagged) { if constexpr (!is_trivially_default_constructible_v) return insert(value, StoredTag{}); else if (use_tags_) return insert_impl(value, StoredTag{}); } return insert_impl(value, StoredTag{}); } vc reduce(const vc &value) const { return eliminate(value, nullptr, nullptr); } template = 0> bool insert(const vc &value, StoredTag tag) { use_tags_ = true; return insert_impl(value, std::move(tag)); } template = 0> int rank(const StoredTag &threshold) const { int result = 0; for (const auto &row : rows_) if (row.accepts(&threshold)) result++; return result; } template = 0> vc reduce(const vc &value, const StoredTag &threshold) const { return eliminate(value, nullptr, &threshold); } #line 6445 template void merge(const LinearBasis &other) ; #line 6463 template LinearBasis intersection(const LinearBasis &other) const ; #line 6501 template LinearBasis operator|(const LinearBasis &other) const { auto result = *this; result.merge(other); return result; } template LinearBasis operator&(const LinearBasis &other) const { return intersection(other); } }; namespace bbla { namespace detail { template vc random_diagonal(int n, const RandomSample &sample) { vc d(n); for (auto &x : d) do { x = sample(); } while (x == F::e0()); return d; } template void scale_diagonal(vc &v, const vc &d) { assert(v.size() == d.size()); repi(i, v.size()) v[i] = F::mul(v[i], d[i]); } #line 6558 } template )> int rank(int rows, int cols, const LinearMap &apply, const TransposeMap &transpose, int trials = 2, const RandomSample &random_sample = random_sample_mint) { using S = typename F::S; assert(rows >= 0 && cols >= 0 && trials > 0); const int d = min(rows, cols); if (d == 0) return 0; int result = 0; repi(trial, trials) { auto dr = detail::random_diagonal(rows, random_sample); auto dc = detail::random_diagonal(cols, random_sample); auto gram = [&](vc &v) { if (cols <= rows) { apply(v); detail::scale_diagonal(v, dr); transpose(v); detail::scale_diagonal(v, dc); } else { transpose(v); detail::scale_diagonal(v, dc); apply(v); detail::scale_diagonal(v, dr); } }; auto m = minimal_polynomial(d, gram, random_sample); int valuation = 0; while (m[valuation] == F::e0()) valuation++; result = max(result, int(m.size()) - 1 - valuation); if (result == d) break; } return result; } template struct LinearSolution { bool solvable; vc solution; vc certificate; CPP_DUMP_DEFINE_DATA(solvable, solution, certificate); }; #line 6691 } namespace internal { inline bool prefer_dense_rank(int rows, int columns, u128 formation_work, u128 action_work, int trials = 1) { const int d = min(rows, columns); const u128 dense = u128(rows) * columns * d + formation_work; const u128 black_box = u128(trials) * d * (u128(rows) + columns + action_work); return dense <= 8 * black_box; } } template > class SparseMatrix { public: using S = typename F::S; using V = vc; using Entry = pair; private: int n_ = 0, m_ = 0; CSR rows_; static CSR canonical_rows(CSR rows) { const int n = rows.template size(); vc sizes(n); for (int i = 0; i < n; i++) { auto row = rows[i]; auto less_index = [](const Entry &a, const Entry &b) { return a.first < b.first; }; if (!is_sorted(row.begin(), row.end(), less_index)) sort(row.begin(), row.end(), less_index); int end = 0; for (const auto &[j, x] : row) { if (end && row[end - 1].first == j) row[end - 1].second = F::add(row[end - 1].second, x); else row[end++] = {j, x}; } int count = 0; for (int k = 0; k < end; k++) if (row[k].second != F::e0()) { if (count != k) row[count] = std::move(row[k]); count++; } sizes[i] = count; } CSR result(sizes); for (int i = 0; i < n; i++) copy_n(rows[i].begin(), sizes[i], result[i].begin()); return result; } public: SparseMatrix() = default; SparseMatrix(int n, int m) : n_(n), m_(m) { assert(n >= 0 && m >= 0); rows_ = CSR(vc(n)); } template SparseMatrix(int n, int m, const vc> &entries) : SparseMatrix(n, m) { static_assert(is_integral_ext && is_integral_ext); vc sizes(n); for (const auto &[i, j, x] : entries) { assert(u128(i) < unsigned(n) && u128(j) < unsigned(m)); sizes[int(i)]++; } CSR rows(sizes); fill(sizes.begin(), sizes.end(), 0); for (const auto &[i, j, x] : entries) rows[int(i)][sizes[int(i)]++] = {int(j), x}; rows_ = canonical_rows(std::move(rows)); } SparseMatrix(int n, int m, initializer_list> entries) : SparseMatrix(n, m, vc>(entries)) {} template SparseMatrix(int columns, const CSR, Erasable> &rows) : SparseMatrix(rows.template size(), columns) { static_assert(is_integral_ext); vc sizes(n_); for (int i = 0; i < n_; i++) sizes[i] = rows[i].template size(); CSR converted(sizes); for (int i = 0; i < n_; i++) { auto row = rows[i]; for (int k = 0; k < sizes[i]; k++) { const auto &[j, x] = row[k]; assert(u128(j) < unsigned(m_)); converted[i][k] = {int(j), x}; } } rows_ = canonical_rows(std::move(converted)); } template explicit SparseMatrix(const Matrix &matrix) { tie(n_, m_) = matrix.template shape(); vc> entries; for (int i = 0; i < n_; i++) for (int j = 0; j < m_; j++) if (matrix[i][j] != F::e0()) entries.emplace_back(i, j, matrix[i][j]); *this = SparseMatrix(n_, m_, entries); } template pair shape() const { return {n_, m_}; } template I size() const { return n_; } template I nnz() const { return rows_.get_elist().size(); } auto operator[](int i) const { assert(0 <= i && i < n_); return rows_[i]; } const CSR &rows() const { return rows_; } auto content() const ; S operator()(int i, int j) const { assert(0 <= i && i < n_ && 0 <= j && j < m_); auto row = rows_[i]; auto it = lower_bound(row.begin(), row.end(), j, [](const Entry &entry, int column) { return entry.first < column; }); return it != row.end() && it->first == j ? it->second : F::e0(); } Matrix to_dense() const ; SparseMatrix transpose() const { vc sizes(m_); for (const auto &[j, x] : rows_.get_elist()) sizes[j]++; SparseMatrix result(m_, n_); result.rows_ = CSR(sizes); fill(sizes.begin(), sizes.end(), 0); for (int i = 0; i < n_; i++) for (const auto &[j, x] : rows_[i]) result.rows_[j][sizes[j]++] = {i, x}; return result; } template SparseMatrix select_rows(const vc &indices) const { static_assert(is_integral_ext); vc sizes(indices.size()); for (int i = 0; i < int(indices.size()); i++) { assert(u128(indices[i]) < unsigned(n_)); sizes[i] = rows_[int(indices[i])].template size(); } SparseMatrix result(indices.size(), m_); result.rows_ = CSR(sizes); for (int i = 0; i < int(indices.size()); i++) copy(rows_[int(indices[i])].begin(), rows_[int(indices[i])].end(), result.rows_[i].begin()); return result; } V operator*(const V &v) const { assert(int(v.size()) == m_); V result(n_, F::e0()); for (int i = 0; i < n_; i++) for (const auto &[j, x] : rows_[i]) result[i] = F::add(result[i], F::mul(x, v[j])); return result; } friend V operator*(const V &v, const SparseMatrix &a) { assert(int(v.size()) == a.n_); V result(a.m_, F::e0()); for (int i = 0; i < a.n_; i++) for (const auto &[j, x] : a.rows_[i]) result[j] = F::add(result[j], F::mul(v[i], x)); return result; } SparseMatrix &scale_rows(const V &scale) ; #line 6908 SparseMatrix &operator*=(const S &scale) { return scale_rows(V(n_, scale)); } SparseMatrix operator*(const S &scale) const { auto result = *this; return result *= scale; } template Matrix operator*(const Matrix &b) const { const auto [m, p] = b.template shape(); assert(m_ == m); Matrix result(n_, p); for (int i = 0; i < n_; i++) for (const auto &[k, x] : rows_[i]) for (int j = 0; j < p; j++) result[i][j] = F::add(result[i][j], F::mul(x, b[k][j])); return result; } template friend Matrix operator*(const Matrix &a, const SparseMatrix &b) { const auto [n, m] = a.template shape(); assert(m == b.n_); Matrix result(n, b.m_); for (int i = 0; i < n; i++) for (int k = 0; k < m; k++) if (a[i][k] != F::e0()) for (const auto &[j, x] : b.rows_[k]) result[i][j] = F::add(result[i][j], F::mul(a[i][k], x)); return result; } Matrix multiply_dense(const SparseMatrix &b) const { assert(m_ == b.n_); Matrix result(n_, b.m_); for (int i = 0; i < n_; i++) for (const auto &[k, x] : rows_[i]) for (const auto &[j, y] : b.rows_[k]) result[i][j] = F::add(result[i][j], F::mul(x, y)); return result; } SparseMatrix operator*(const SparseMatrix &b) const { assert(m_ == b.n_); V value(b.m_, F::e0()); vc seen(b.m_, -1), touched; vc> entries; for (int i = 0; i < n_; i++) { touched.clear(); for (const auto &[k, x] : rows_[i]) for (const auto &[j, y] : b.rows_[k]) { if (seen[j] != i) seen[j] = i, value[j] = F::e0(), touched.push_back(j); value[j] = F::add(value[j], F::mul(x, y)); } for (int j : touched) if (value[j] != F::e0()) entries.emplace_back(i, j, value[j]); } return SparseMatrix(n_, b.m_, entries); } template ) &> I rank(int trials = 2, Sample &&sample = bbla::random_sample_mint) const { assert(trials > 0); if (n_ == 0 || m_ == 0 || nnz() == 0) return I(0); if (internal::prefer_dense_rank(n_, m_, u128(n_) * m_ + nnz(), nnz(), trials)) return to_dense().template rank(); auto apply = [&](V &v) { v = *this * v; }; auto transpose_apply = [&](V &v) { v = v * *this; }; auto random = [&]() -> S { return sample(); }; return I(bbla::rank(n_, m_, apply, transpose_apply, trials, random)); } #line 7009 }; template > class LinearMatroid { public: using S = typename F::S; private: int dimension_ = 0; vvc columns_; vc selected_; vc used_; LinearBasis basis_; public: LinearMatroid() = default; LinearMatroid(int dimension, const vvc &columns) : LinearMatroid(dimension, vvc(columns)) {} LinearMatroid(int dimension, vvc &&columns) : dimension_(dimension), columns_(std::move(columns)), used_(columns_.size()), basis_(dimension) { assert(dimension >= 0); for (const auto &column : columns_) assert(int(column.size()) == dimension_); } template explicit LinearMatroid(const Matrix &matrix) : LinearMatroid(matrix.template shape().first, gen_vec(matrix.template shape().second, [&](int e) { return matrix.column(e); })) {} CPP_DUMP_DEFINE_DATA(dimension_, columns_, selected_); int size() const { return int(columns_.size()); } int dimension() const ; const vvc &columns() const ; Matrix matrix() const { Matrix result(dimension_, size()); for (int e = 0; e < size(); e++) for (int i = 0; i < dimension_; i++) result[i][e] = columns_[e][i]; return result; } template void build(const vc &independent) { selected_.assign(ALL(independent)); fill(used_.begin(), used_.end(), 0); basis_.clear(); for (auto value : independent) { assert(u128(value) < unsigned(size())); const int e = int(value); assert(!used_[e]); used_[e] = 1; bool inserted = basis_.insert(columns_[e]); assert(inserted); (void)inserted; } } }; namespace internal { template class LinearRepresentationBuilder { using S = typename F::S; int dimension_, size_; conditional_t>, Matrix> data_; public: LinearRepresentationBuilder(int dimension, int size) : dimension_(dimension), size_(size), data_([&] { if constexpr (Sparse) return vc>{}; else return Matrix(dimension, size); }()) {} void set(int element, int coordinate, const S &value) { if constexpr (Sparse) { if (value != F::e0()) data_.emplace_back(coordinate, element, value); } else data_[coordinate][element] = value; } auto finish() && { if constexpr (Sparse) return SparseMatrix(dimension_, size_, data_); else return std::move(data_); } }; } namespace internal::linear_matroid_detail { template int element_count(const Matrix &matrix) ; template int element_count(const LinearMatroid &matroid) ; template vvc compressed_columns(const Matrix &matrix) ; template vvc compressed_columns(const LinearMatroid &matroid) ; template pair, vc>> parity_representation(const M &matroid, const vc> &pairs) { const int n = element_count(matroid); vc used(n); for (auto [a, b] : pairs) { assert(u128(a) < unsigned(n) && u128(b) < unsigned(n)); assert(u128(a) != u128(b) && !used[a] && !used[b]); used[a] = used[b] = 1; } auto compressed = compressed_columns(matroid); const int m = int(pairs.size()); vvc columns; vc> work_pairs; columns.reserve(2 * m); work_pairs.reserve(m); for (int e = 0; e < m; e++) { auto [a, b] = pairs[e]; columns.push_back(std::move(compressed[a])); columns.push_back(std::move(compressed[b])); work_pairs.emplace_back(2 * e, 2 * e + 1); } return {std::move(columns), std::move(work_pairs)}; } inline vc> consecutive_pairs(int size) { assert(size % 2 == 0); vc> pairs; pairs.reserve(size / 2); for (int e = 0; e < size; e += 2) pairs.emplace_back(e, e + 1); return pairs; } #line 7260 } namespace internal::linear_matroid_detail { template int sparse_intersection_rank(const SparseMatrix &a, const SparseMatrix &b, const vc &active, Sample &sample) ; #line 7291 template vc> sparse_parity_pairs(int size, const vc> &pairs) { static_assert(is_integral_ext && is_integral_ext); vc used(size); vc> result; result.reserve(pairs.size()); for (auto [a, b] : pairs) { assert(u128(a) < unsigned(size) && u128(b) < unsigned(size)); assert(u128(a) != u128(b) && !used[int(a)] && !used[int(b)]); used[int(a)] = used[int(b)] = 1; result.emplace_back(int(a), int(b)); } return result; } template int sparse_parity_rank(const SparseMatrix &matrix, const vc> &pairs, const vc &active, Sample &sample) { using S = typename F::S; const auto shape = matrix.template shape(); const int d = shape.first, n = shape.second, m = pairs.size(); if (!d || !m) return 0; vc diagonal(m, F::e0()); for (int e = 0; e < m; e++) if (active[e]) diagonal[e] = sample(); auto apply = [&](vc &v) { auto middle = v * matrix; vc twisted(n, F::e0()); for (int e = 0; e < m; e++) { const auto [a, b] = pairs[e]; twisted[a] = F::mul(diagonal[e], middle[b]); twisted[b] = F::minus(F::mul(diagonal[e], middle[a])); } v = matrix * twisted; }; auto transpose = [&](vc &v) { apply(v); for (auto &x : v) x = F::minus(x); }; auto random = [&]() -> S { return sample(); }; return bbla::rank(d, d, apply, transpose, 1, random) / 2; } template optional> compact_nonzero_rows(const SparseMatrix &matrix) { const int d = matrix.template shape().first; vc indices; for (int i = 0; i < d; i++) if (!matrix[i].empty()) indices.push_back(i); if (int(indices.size()) == d) return nullopt; return matrix.select_rows(indices); } template class SparseIntersectionRank { using S = typename F::S; const SparseMatrix &original_a_, &original_b_; optional> compact_a_, compact_b_, transpose_b_; const SparseMatrix &a() const { return compact_a_ ? *compact_a_ : original_a_; } const SparseMatrix &b() const { return compact_b_ ? *compact_b_ : original_b_; } public: bool dense; SparseIntersectionRank(const SparseMatrix &first, const SparseMatrix &second) : original_a_(first), original_b_(second), compact_a_(compact_nonzero_rows(first)), compact_b_(compact_nonzero_rows(second)) { const auto sa = a().template shape(), sb = b().template shape(); const int n = sa.second; assert(n == sb.second); vc ca(n), cb(n); for (const auto &[e, x] : a().rows().get_elist()) ca[e]++; for (const auto &[e, x] : b().rows().get_elist()) cb[e]++; u128 products = 0; for (int e = 0; e < n; e++) products += u128(ca[e]) * cb[e]; const u128 work = u128(n) + a().template nnz() + b().template nnz(); dense = internal::prefer_dense_rank(sa.first, sb.first, u128(sa.first) + sb.first + work + products, work); if (dense) transpose_b_.emplace(b().transpose()); } template int operator()(const vc &active, Sample &sample) const { const auto sa = a().template shape(), sb = b().template shape(); if (!sa.first || !sb.first || !sa.second) return 0; if (!dense) return sparse_intersection_rank(a(), b(), active, sample); vc diagonal(sa.second, F::e0()); for (int e = 0; e < sa.second; e++) if (active[e]) diagonal[e] = sample(); auto weighted = *transpose_b_; weighted.scale_rows(diagonal); return a().multiply_dense(weighted).template rank(); } }; template class SparseParityRank { using S = typename F::S; const SparseMatrix &original_; const vc> &pairs_; optional> compact_, transpose_; u128 products_ = 0; const SparseMatrix &matrix() const { return compact_ ? *compact_ : original_; } public: bool dense; SparseParityRank(const SparseMatrix &representation, const vc> &pairs) : original_(representation), pairs_(pairs), compact_(compact_nonzero_rows(representation)) { const auto shape = matrix().template shape(); vc count(shape.second); for (const auto &[e, x] : matrix().rows().get_elist()) count[e]++; for (auto [a, b] : pairs_) products_ += u128(count[a]) * count[b]; const u128 work = u128(shape.second) + pairs_.size() + matrix().template nnz(); dense = internal::prefer_dense_rank(shape.first, shape.first, shape.first + work + 2 * products_, work); if (dense) transpose_.emplace(matrix().transpose()); } template int operator()(const vc &active, Sample &sample) const { const int d = matrix().template shape().first; if (!d || products_ == 0) return 0; if (!dense) return sparse_parity_rank(matrix(), pairs_, active, sample); const int n = matrix().template shape().second; vc> entries; entries.reserve(2 * pairs_.size()); for (int e = 0; e < int(pairs_.size()); e++) if (active[e]) { const auto [a, b] = pairs_[e]; S x = sample(); entries.emplace_back(a, b, x); entries.emplace_back(b, a, F::minus(x)); } const SparseMatrix alternating(n, n, entries); int rank = matrix().multiply_dense(alternating * *transpose_).template rank(); assert(rank % 2 == 0); return rank / 2; } }; #line 7481 } namespace internal::linear_matroid_detail { template int dense_parity_size(const M &matroid, const vc> &pairs, Sample &sample, int trials) ; #line 7531 } template , int> = 0> int linear_matroid_parity_size(const Matrix &matroid, const vc> &pairs, Sample &&sample, int trials = 1) { return internal::linear_matroid_detail::dense_parity_size(matroid, pairs, sample, trials); } template , int> = 0> int linear_matroid_parity_size(const Matrix &matroid, Sample &&sample, int trials = 1) { const int n = matroid.template shape().second; auto pairs = internal::linear_matroid_detail::consecutive_pairs(n); return linear_matroid_parity_size(matroid, pairs, std::forward(sample), trials); } template , int> = 0> vc linear_matroid_parity_restore(const Matrix &matroid, const vc> &pairs, Sample &&sample, int trials = 1) ; template , int> = 0> vc linear_matroid_parity_restore(const Matrix &matroid, Sample &&sample, int trials = 1) ; template int linear_matroid_parity_size(const Matrix &matroid, const vc> &pairs, int trials = 1) { return linear_matroid_parity_size(matroid, pairs, random_modint, trials); } template int linear_matroid_parity_size(const Matrix &matroid, int trials = 1) { return linear_matroid_parity_size(matroid, random_modint, trials); } template int linear_matroid_parity_size(const Matrix &matroid, initializer_list> pairs, int trials = 1) { return linear_matroid_parity_size(matroid, vc>(pairs), trials); } template vc linear_matroid_parity_restore(const Matrix &matroid, const vc> &pairs, int trials = 1) ; template vc linear_matroid_parity_restore(const Matrix &matroid, int trials = 1) ; template vc linear_matroid_parity_restore(const Matrix &matroid, initializer_list> pairs, int trials = 1) ; template , int> = 0> int linear_matroid_parity_size(const LinearMatroid &matroid, const vc> &pairs, Sample &&sample, int trials = 1) { return internal::linear_matroid_detail::dense_parity_size(matroid, pairs, sample, trials); } template , int> = 0> int linear_matroid_parity_size(const LinearMatroid &matroid, Sample &&sample, int trials = 1) { auto pairs = internal::linear_matroid_detail::consecutive_pairs(matroid.size()); return linear_matroid_parity_size(matroid, pairs, std::forward(sample), trials); } template , int> = 0> vc linear_matroid_parity_restore(const LinearMatroid &matroid, const vc> &pairs, Sample &&sample, int trials = 1) ; template , int> = 0> vc linear_matroid_parity_restore(const LinearMatroid &matroid, Sample &&sample, int trials = 1) ; template int linear_matroid_parity_size(const LinearMatroid &matroid, const vc> &pairs, int trials = 1) { return linear_matroid_parity_size(matroid, pairs, random_modint, trials); } template int linear_matroid_parity_size(const LinearMatroid &matroid, int trials = 1) { return linear_matroid_parity_size(matroid, random_modint, trials); } template int linear_matroid_parity_size(const LinearMatroid &matroid, initializer_list> pairs, int trials = 1) { return linear_matroid_parity_size(matroid, vc>(pairs), trials); } template vc linear_matroid_parity_restore(const LinearMatroid &matroid, const vc> &pairs, int trials = 1) ; template vc linear_matroid_parity_restore(const LinearMatroid &matroid, int trials = 1) ; template vc linear_matroid_parity_restore(const LinearMatroid &matroid, initializer_list> pairs, int trials = 1) ; template , int> = 0> int linear_matroid_parity_size(const SparseMatrix &matroid, const vc> &pairs, Sample &&sample, int trials = 1) { assert(trials >= 1); using namespace internal::linear_matroid_detail; auto work_pairs = sparse_parity_pairs(matroid.template shape().second, pairs); SparseParityRank rank(matroid, work_pairs); vc active(pairs.size(), 1); int best = 0; for (int trial = 0; trial < trials; trial++) best = max(best, rank(active, sample)); return best; } template , int> = 0> int linear_matroid_parity_size(const SparseMatrix &matroid, Sample &&sample, int trials = 1) { auto pairs = internal::linear_matroid_detail::consecutive_pairs(matroid.template shape().second); return linear_matroid_parity_size(matroid, pairs, std::forward(sample), trials); } template , int> = 0> vc linear_matroid_parity_restore(const SparseMatrix &matroid, const vc> &pairs, Sample &&sample, int trials = 1) ; #line 7827 template , int> = 0> vc linear_matroid_parity_restore(const SparseMatrix &matroid, Sample &&sample, int trials = 1) ; template int linear_matroid_parity_size(const SparseMatrix &matroid, const vc> &pairs, int trials = 1) { return linear_matroid_parity_size(matroid, pairs, random_modint, trials); } template int linear_matroid_parity_size(const SparseMatrix &matroid, int trials = 1) { return linear_matroid_parity_size(matroid, random_modint, trials); } template int linear_matroid_parity_size(const SparseMatrix &matroid, initializer_list> pairs, int trials = 1) { return linear_matroid_parity_size(matroid, vc>(pairs), trials); } template vc linear_matroid_parity_restore(const SparseMatrix &matroid, const vc> &pairs, int trials = 1) ; template vc linear_matroid_parity_restore(const SparseMatrix &matroid, int trials = 1) ; template vc linear_matroid_parity_restore(const SparseMatrix &matroid, initializer_list> pairs, int trials = 1) ; #line 7914 template struct Edge { int from, to; Cost cost; int index; CPP_DUMP_DEFINE_DATA(from, to, cost, index); Edge() : from(-1), to(-1), cost{}, index(-1) {} Edge(int s, int t, Cost c, int i = -1) : from(s), to(t), cost(c), index(i) {} operator int() const { return to; } bool operator<(const Edge &rhs) const { return cost < rhs.cost; } }; template <> struct Edge { int from, to, index; static constexpr ll cost = 1; CPP_DUMP_DEFINE_DATA(from, to, cost, index); Edge() : from(-1), to(-1), index(-1) {} Edge(int s, int t, int i = -1) : from(s), to(t), index(i) {} operator int() const { return to; } bool operator<(const Edge &) const { return false; } }; #line 7959 template struct Graph { using E = Edge; protected: template > struct InternalEdge { int to, index; C cost; }; template struct InternalEdge { int to, index; static constexpr ll cost = 1; }; using GE = conditional_t>; using Weight = decay_t; int n = 0, m = 0, era = 0; CSR g; vc eid_to_elist_id; static E make_edge(int from, int to, const Weight &cost, int index) { if constexpr (is_void_v) return E(from, to, index); else return E(from, to, cost, index); } struct OutEdgeRow; struct OutEdgeIter { using iterator_category = input_iterator_tag; using value_type = E; using difference_type = ptrdiff_t; using pointer = const E *; using reference = const E &; private: friend struct OutEdgeRow; int from = -1; typename vc::const_iterator it; mutable E e; OutEdgeIter(int from, typename vc::const_iterator it) : from(from), it(it) {} public: OutEdgeIter() = default; reference operator*() const { if constexpr (is_erasable) return *it; else { e = make_edge(from, it->to, it->cost, it->index); return e; } } pointer operator->() const { return &**this; } OutEdgeIter &operator++() { ++it; return *this; } OutEdgeIter operator++(int) { auto res = *this; ++*this; return res; } bool operator==(const OutEdgeIter &rhs) const { return it == rhs.it; } bool operator!=(const OutEdgeIter &rhs) const { return !(*this == rhs); } }; struct OutEdgeRow { private: const Graph *g; int from, l, r; OutEdgeIter iter(int pos) const { return {from, g->g.get_elist().begin() + pos}; } public: OutEdgeRow(const Graph *g, int from) : g(g), from(from), l(g->g.offset(from)), r(l + g->g[from].size()) {} OutEdgeIter begin() const { return iter(l); } OutEdgeIter end() const { return iter(r); } template I size() const { return r - l; } bool empty() const { return l == r; } E operator[](int i) const { assert(0 <= i && i < size()); return g->get_edge(from, l + i); } E front() const { assert(!empty()); return (*this)[0]; } E back() const { assert(!empty()); return (*this)[size() - 1]; } }; E get_edge(int from, int pos) const ; template void build(F input_edge) { vc row_sizes(n); repi(i, m) { auto [u, v, w] = input_edge(i); assert(0 <= u && u < n && 0 <= v && v < n); row_sizes[u]++; if constexpr (!is_directed) if (u != v) row_sizes[v]++; } g = CSR(row_sizes); if constexpr (is_erasable) eid_to_elist_id.assign((is_directed ? 1 : 2) * m, -1); vc cnt(n); repi(i, m) { auto [u, v, w] = input_edge(i); int j = cnt[u]++; int k = g.offset(u) + j; if constexpr (is_erasable) g[u][j] = make_edge(u, v, w, i); else if constexpr (is_void_v) g[u][j] = GE{int(v), i}; else g[u][j] = GE{int(v), i, w}; if constexpr (is_erasable) { int id = is_directed ? i : 2 * i + (u <= v); eid_to_elist_id[id] = k; } if constexpr (!is_directed) { if (u != v) { j = cnt[v]++; k = g.offset(v) + j; if constexpr (is_erasable) g[v][j] = make_edge(v, u, w, i); else if constexpr (is_void_v) g[v][j] = GE{int(u), i}; else g[v][j] = GE{int(u), i, w}; if constexpr (is_erasable) eid_to_elist_id[2 * i + (v <= u)] = k; } } } } public: local(auto content() const { return pair{n, edges()}; }) Graph() {} template Graph(int n, const vc> &es) : n(n), m(es.size()), era(0) { build(LMD(i, (tuple{es[i].first, es[i].second, Weight(1)}))); } template , int> = 0> Graph(int n, const vc> &es, const Weight &dflt_cost) : n(n), m(es.size()), era(0) { build(LMD(i, (tuple{es[i].first, es[i].second, dflt_cost}))); } template && !is_void_v, int> = 0> Graph(int n, const vc> &es) : n(n), m(es.size()), era(0) { build(LMD(i, es[i])); } Graph(int n, const vc &es) : n(n), m(es.size()), era(0) { build(LMD(i, (tuple{es[i].from, es[i].to, es[i].cost}))); } template I size() const { return n; } auto out_edges(int v) const { return OutEdgeRow(this, v); } #line 8189 vc edges() const ; #line 8267 private: #line 8293 }; template Graph(int, const vc> &) -> Graph; template Graph(int, const vc> &) -> Graph; template Graph(int, const vc> &, const Cost &) -> Graph; template Graph(int, const vc> &) -> Graph; template using GraphDirected = Graph; template using GraphUndirected = Graph; #line 8327 namespace internal { struct BipartiteGraphIndex { vc left, right, index; CSR adjacency; template BipartiteGraphIndex(const GraphUndirected &graph, const vc &color) { const int n = graph.template size(); assert(int(color.size()) == n); index.resize(n); for (int v = 0; v < n; v++) { assert(color[v] == 0 || color[v] == 1); auto &side = color[v] == 1 ? right : left; index[v] = side.size(); side.push_back(v); } vc degree(left.size()); for (int u = 0; u < int(left.size()); u++) degree[u] = graph.out_edges(left[u]).size(); adjacency = CSR(degree); for (int v = 0; v < n; v++) { int next = color[v] == 0 ? adjacency.offset(index[v]) : 0; for (auto edge : graph.out_edges(v)) { assert((color[v] == 1) != (color[edge.to] == 1)); if (color[v] == 0) adjacency.get_elist()[next++] = index[edge.to]; } } } }; } class BipartiteMatchingState { public: struct SearchResult { vc left, right, parent_right; optional free_right; CPP_DUMP_DEFINE_DATA(left, right, parent_right, free_right); }; private: int right_count = 0, matched = 0; CSR adjacency_; vc left_mate_, right_mate_; vc left_vertices_, right_vertices_, vertex_index_; explicit BipartiteMatchingState(internal::BipartiteGraphIndex indexed) : right_count(indexed.right.size()), adjacency_(move(indexed.adjacency)), left_mate_(indexed.left.size(), -1), right_mate_(right_count, -1), left_vertices_(move(indexed.left)), right_vertices_(move(indexed.right)), vertex_index_(move(indexed.index)) {} public: template BipartiteMatchingState(const GraphUndirected &graph, const vc &color) : BipartiteMatchingState(internal::BipartiteGraphIndex(graph, color)) {} BipartiteMatchingState(int right_vertices, CSR adjacency) : right_count(right_vertices), adjacency_(move(adjacency)), left_mate_(adjacency_.template size(), -1), right_mate_(right_vertices, -1) { assert(right_vertices >= 0); for (int v : adjacency_.get_elist()) assert(0 <= v && v < right_count); } template BipartiteMatchingState(int right_vertices, const vvc &adjacency) : BipartiteMatchingState(right_vertices, CSR(adjacency)) { for (const auto &row : adjacency) for (auto v : row) assert(u128(v) < unsigned(right_vertices)); } template BipartiteMatchingState(int right_vertices, initializer_list> adjacency) : BipartiteMatchingState(right_vertices, vvc(adjacency)) {} template BipartiteMatchingState(int right_vertices, const CSR &adjacency) : BipartiteMatchingState(right_vertices, CSR(adjacency)) { for (int u = 0; u < adjacency.template size(); u++) for (auto v : adjacency[u]) assert(u128(v) < unsigned(right_vertices)); } int left_size() const { return adjacency_.template size(); } int right_size() const { return right_count; } const CSR &adjacency() const { return adjacency_; } CPP_DUMP_DEFINE_DATA(left_vertices_, right_vertices_, adjacency_, left_mate_, right_mate_); int left_vertex(int u) const { assert(0 <= u && u < left_size()); return left_vertices_.empty() ? u : left_vertices_[u]; } int right_vertex(int v) const { assert(0 <= v && v < right_size()); return right_vertices_.empty() ? v : right_vertices_[v]; } optional left_index(int vertex) const { if (vertex_index_.empty()) return 0 <= vertex && vertex < left_size() ? optional(vertex) : nullopt; if (vertex < 0 || vertex >= int(vertex_index_.size())) return nullopt; const int u = vertex_index_[vertex]; return u < left_size() && left_vertices_[u] == vertex ? optional(u) : nullopt; } vc> matching() const { vc> result; result.reserve(matched); for (int u = 0; u < left_size(); u++) if (left_mate_[u] != -1) result.emplace_back(left_vertex(u), right_vertex(left_mate_[u])); return result; } void clear() { fill(ALL(left_mate_), -1), fill(ALL(right_mate_), -1); matched = 0; } template SearchResult search(int source) const { assert(0 <= source && source < left_size() && left_mate_[source] == -1); SearchResult result; result.parent_right.assign(right_count, -1); vc seen_left(left_size()); seen_left[source] = true; result.left.eb(source); for (int head = 0; head < int(result.left.size()); head++) { const int u = result.left[head]; for (int v : adjacency_[u]) if (result.parent_right[v] == -1) { result.parent_right[v] = u; if constexpr (CollectRight) result.right.eb(v); const int next = right_mate_[v]; if (next == -1) { result.free_right = v; return result; } if (!seen_left[next]) seen_left[next] = true, result.left.eb(next); } } return result; } bool augment(int source) { auto result = search(source); if (!result.free_right) return false; for (int v = *result.free_right; v != -1;) { const int u = result.parent_right[v], previous = left_mate_[u]; left_mate_[u] = v, right_mate_[v] = u; v = previous; } matched++; return true; } #line 8542 }; template , class Cost, bool is_erasable, class Color, class Sample = decltype(random_modint) &, bool Sparse = false> auto transversal_linear_representation(const GraphUndirected &graph, const vc &color, Sample &&sample = random_modint) { internal::BipartiteGraphIndex indexed(graph, color); const int n = indexed.left.size(), dimension = indexed.right.size(); internal::LinearRepresentationBuilder columns(dimension, n); vc seen(dimension, -1); for (int e = 0; e < n; e++) for (int v : indexed.adjacency[e]) { if (seen[v] == e) continue; seen[v] = e; columns.set(e, v, sample()); } return std::move(columns).finish(); } template , class Sample = decltype(random_modint) &, class I = int, bool Sparse = false> auto transversal_linear_representation(int right_vertices, const vvc &adjacency, Sample &&sample = random_modint) { assert(right_vertices >= 0); const int n = adjacency.size(); internal::LinearRepresentationBuilder columns(right_vertices, n); vc seen(right_vertices, -1); for (int e = 0; e < n; e++) for (auto value : adjacency[e]) { assert(u128(value) < unsigned(right_vertices)); const int v = int(value); if (seen[v] == e) continue; seen[v] = e; columns.set(e, v, sample()); } return std::move(columns).finish(); } template , class Sample = decltype(random_modint) &, class I = int, bool erasable = false, bool Sparse = false> auto transversal_linear_representation(int right_vertices, const CSR &adjacency, Sample &&sample = random_modint) { assert(right_vertices >= 0); const int n = adjacency.size(); internal::LinearRepresentationBuilder columns(right_vertices, n); vc seen(right_vertices, -1); for (int e = 0; e < n; e++) for (auto value : adjacency[e]) { assert(u128(value) < unsigned(right_vertices)); const int v = int(value); if (seen[v] == e) continue; seen[v] = e; columns.set(e, v, sample()); } return std::move(columns).finish(); } template , class Sample = decltype(random_modint) &, class I = int, bool Sparse = false> auto transversal_linear_representation(int right_vertices, initializer_list> adjacency, Sample &&sample = random_modint) { return transversal_linear_representation(right_vertices, vvc(adjacency), std::forward(sample)); } class TransversalMatroid { BipartiteMatchingState matching; vc selected; public: template TransversalMatroid(const GraphUndirected &graph, const vc &color) : matching(graph, color), selected(matching.left_size()) {} template TransversalMatroid(int right_vertices, vvc adjacency) : matching(right_vertices, adjacency), selected(adjacency.size()) {} CPP_DUMP_DEFINE_DATA(matching, selected); int size() const { return matching.left_size(); } int vertex(int e) const { return matching.left_vertex(e); } optional element(int vertex) const { return matching.left_index(vertex); } template , class Sample = decltype(random_modint) &> SparseMatrix sparse_linear_representation(Sample &&sample = random_modint) const { return transversal_linear_representation(matching.right_size(), matching.adjacency(), std::forward(sample)); } template void build(const vc &s) { fill(ALL(selected), false); matching.clear(); for (auto value : s) { assert(u128(value) < unsigned(size())); const int e = int(value); assert(!selected[e]); selected[e] = true; const bool added = matching.augment(e); assert(added); (void)added; } } }; void main2() { LL(L, R); JAG(ll, 2 * L, V); offset(V, -1); vpll E; rep(i, 2 * L) fe(v : V[i]) E.eb(i, 2 * L + v); TransversalMatroid tm(GraphUndirected(2 * L + R, E), concat(vl(2 * L, 0), vl(R, 1))); dump(tm); local(dump(linear_matroid_parity_restore(tm.sparse_linear_representation()))); ll ans = L + linear_matroid_parity_size(tm.sparse_linear_representation()); PRINT(ans); } void test() { } 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(); #line 8746 CERR("\n[SINGLE_TESTCASE]\n\n", "36"); main2(); #line 8761 } }; Main main_dummy; int main() {} // submit-code: hash=66bed88db000 source=66bed88db0003b2cf2e4737ba89702e4b00120ec86341ac99026a3b8dff9105f input=85632aaa77d19fe7e645b511983fff0e9de0d45cd4db5a6e74e30c59c4cae875 body=db0744225f7d8f01468aff543cfea4de04ae7907d2c694b5c926bf6230af403d