結果
| 問題 | No.3863 Almost Bipartite Matching |
| コンテスト | |
| ユーザー |
miscalc
|
| 提出日時 | 2026-12-01 09:23:29 |
| 結果 |
AC
不安定
|
| 実行時間 | 845 ms / 2,000 ms |
| + 538µs | |
| コード長 | 128,028 bytes |
| 記録 | |
| コンパイル時間 | 5,870 ms |
| コンパイル使用メモリ | 448,792 KB |
| 実行使用メモリ | 414,760 KB |
| 最終ジャッジ日時 | 2026-12-06 02:10:49 |
| 合計ジャッジ時間 | 50,594 ms |
|
ジャッジサーバーID (参考情報) |
judge2_0 / judge6_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 59 |
ソースコード
// 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 <bits/stdc++.h>
using namespace std;
#if __cplusplus > 202002L && defined(__STDCPP_FLOAT128_T__)
#include <stdfloat>
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 <cassert>
using namespace std;
using ld = decltype(EPS);
using ll = long long;
using uint = unsigned int;
using ull = unsigned long long;
using pll = pair<ll, ll>;
using tlll = tuple<ll, ll, ll>;
using tllll = tuple<ll, ll, ll, ll>;
#define vc vector
template <class T>
using vvc = vc<vc<T>>;
template <class T>
using vvvc = vc<vc<vc<T>>>;
using vb = vc<bool>;
using vl = vc<ll>;
using vpll = vc<pll>;
using vtlll = vc<tlll>;
using vtllll = vc<tllll>;
using vstr = vc<string>;
using vvb = vvc<bool>;
using vvl = vvc<ll>;
template <class T>
using pql = priority_queue<T, vc<T>, greater<T>>;
template <class T>
using pqg = priority_queue<T>;
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, 3>{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 <class T, class U, class P>
constexpr pair<T, U> &operator+=(pair<T, U> &a, const P &b)
{
a.first += b.first;
a.second += b.second;
return a;
}
template <class T, class U, class P>
constexpr pair<T, U> operator+(pair<T, U> a, const P &b) { return a += b; }
template <class T, class U, class P>
constexpr pair<T, U> &operator-=(pair<T, U> &a, const P &b)
{
a.first -= b.first;
a.second -= b.second;
return a;
}
template <class T, class U, class P>
constexpr pair<T, U> operator-(pair<T, U> a, const P &b) { return a -= b; }
template <class T, class U>
constexpr pair<T, U> operator-(pair<T, U> a)
{
a.first = -a.first;
a.second = -a.second;
return a;
}
template <class T, size_t n, class A>
constexpr array<T, n> &operator+=(array<T, n> &a, const A &b)
{
for (size_t i = 0; i < n; i++)
a[i] += b[i];
return a;
}
template <class T, size_t n, class A>
constexpr array<T, n> operator+(array<T, n> a, const A &b) { return a += b; }
template <class T, size_t n, class A>
constexpr array<T, n> &operator-=(array<T, n> &a, const A &b)
{
for (size_t i = 0; i < n; i++)
a[i] -= b[i];
return a;
}
template <class T, size_t n, class A>
constexpr array<T, n> operator-(array<T, n> a, const A &b) { return a -= b; }
template <class T, size_t n>
constexpr array<T, n> operator-(array<T, n> a)
{
for (auto &ai : a)
ai = -ai;
return a;
}
namespace internal
{
template <size_t... I, class A, class B>
constexpr auto &tuple_add_impl(A &a, const B &b, const index_sequence<I...>)
;
template <size_t... I, class A, class B>
constexpr auto &tuple_sub_impl(A &a, const B &b, const index_sequence<I...>)
;
template <size_t... I, class A>
constexpr auto &tuple_neg_impl(A &a, const index_sequence<I...>)
;
};
template <class... Ts, class Tp>
constexpr tuple<Ts...> &operator+=(tuple<Ts...> &a, const Tp &b)
{ return internal::tuple_add_impl(a, b, make_index_sequence<tuple_size_v<tuple<Ts...>>>{}); }
template <class... Ts, class Tp>
constexpr tuple<Ts...> operator+(tuple<Ts...> a, const Tp &b) { return a += b; }
template <class... Ts, class Tp>
constexpr tuple<Ts...> &operator-=(tuple<Ts...> &a, const Tp &b)
{ return internal::tuple_sub_impl(a, b, make_index_sequence<tuple_size_v<tuple<Ts...>>>{}); }
template <class... Ts, class Tp>
constexpr tuple<Ts...> operator-(tuple<Ts...> a, const Tp &b) { return a -= b; }
template <class... Ts>
constexpr tuple<Ts...> operator-(tuple<Ts...> a)
{
internal::tuple_neg_impl(a, make_index_sequence<sizeof...(Ts)>{});
return a;
}
#line 512
template <class T>
constexpr bool is_integral_ext = is_integral_v<T> || is_same_v<T, i128> || is_same_v<T, u128>;
template <class T>
constexpr bool is_signed_ext = is_signed_v<T> || is_same_v<T, i128>;
template <class T>
constexpr bool is_unsigned_ext = is_unsigned_v<T> || is_same_v<T, u128>;
#line 531
template <class T>
struct make_unsigned_ext
{
using type = make_unsigned_t<T>;
};
template <>
struct make_unsigned_ext<i128>
{
using type = u128;
};
template <>
struct make_unsigned_ext<u128>
{
using type = u128;
};
template <class T>
using make_unsigned_ext_t = typename make_unsigned_ext<T>::type;
template <class T>
struct make_signed_ext
{
using type = make_signed_t<T>;
};
template <>
struct make_signed_ext<i128>
{
using type = i128;
};
template <>
struct make_signed_ext<u128>
{
using type = i128;
};
template <class T>
using make_signed_ext_t = typename make_signed_ext<T>::type;
template <class T>
constexpr bool is_negative(T x)
{
static_assert(is_integral_ext<T>);
if constexpr (is_signed_ext<T>) return x < 0;
return false;
}
template <class T, bool = is_integral_ext<T>>
struct unsigned_arithmetic { using type = T; };
template <class T>
struct unsigned_arithmetic<T, true>
{
static_assert(!is_same_v<T, bool>);
using type = common_type_t<unsigned int, make_unsigned_ext_t<T>>;
};
template <class T>
using unsigned_arithmetic_t = typename unsigned_arithmetic<T>::type;
#line 633
namespace default_infty_detail
{
template <class T>
struct is_product : false_type {};
template <class T, class U>
struct is_product<pair<T, U>> : true_type {};
template <class... Ts>
struct is_product<tuple<Ts...>> : true_type {};
template <class T, size_t n>
struct is_product<array<T, n>> : true_type {};
template <class T, class = void>
struct has_infty : false_type {};
template <class T>
struct has_infty<T, void_t<decltype(T::infty())>> : true_type {};
template <class T>
inline constexpr bool unsupported = false;
}
#line 701
template <class T, class U>
inline bool chmin(T &a, U b) ;
namespace template_math_detail
{
#line 733
}
#line 763
template <class T = ll, class U, class V, typename = enable_if_t<is_integral_ext<U> && is_integral_ext<V>>>
inline constexpr T safemod(U a, V b)
{
const T x = T(a), y = T(b);
if constexpr (is_signed_ext<T>)
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 <class T = ll, class V>
inline T SZ(const V &x) { return x.size(); }
#define eb emplace_back
#define LMD(x, fx) ([&](const auto &x) { return fx; })
template <class F>
auto gen_vec(int n, const F &f)
;
namespace template_vector_detail
{
template <class T, size_t depth>
struct nested_vector
{
using type = vc<typename nested_vector<T, depth - 1>::type>;
};
template <class T>
struct nested_vector<T, 0>
{
using type = T;
};
#line 1024
}
#line 1039
template <class V, class T>
void fill(V &v, const T &value)
{
if constexpr (is_assignable_v<decltype(*std::begin(v)), const T &>)
std::fill(std::begin(v), std::end(v), value);
else
for (auto &row : v) fill(row, value);
}
#line 1088
template <class T>
vc<T> concat(const vvc<T> &vs)
{
vc<T> res;
for (cauto &v : vs)
res.insert(res.end(), ALL(v));
return res;
}
template <class T>
vc<T> concat(const vc<T> &v) { return v; }
template <class T, class... Ts>
vc<T> concat(vc<T> v, const vc<Ts> &...vs)
{
(v.insert(v.end(), ALL(vs)), ...);
return v;
}
#line 1158
template <class T, auto x = nullptr>
constexpr decltype(auto) resolved_infty()
;
#line 1175
namespace internal
{
template <class M, class I, class = void>
struct HasMonoidPow : false_type {};
template <class M, class I>
struct HasMonoidPow<M, I, void_t<decltype(M::pow(declval<const typename M::S &>(), declval<I>()))>> : true_type {};
}
namespace internal_monoid_power
{
#line 1211
}
#line 1337
template <class V>
V reversed(const V &v) { return V(v.rbegin(), v.rend()); }
#line 1385
template <class T>
vvc<T> top(const vvc<T> &a)
{
if (a.empty())
return {};
const int n = a.size(), m = a[0].size();
vvc<T> b(m, vc<T>(n));
repi(i, n)
{
assert(SZ<int>(a[i]) == m);
repi(j, m) b[j][i] = a[i][j];
}
return b;
}
vstr top(const vstr &a)
{
vvc<char> a_(a.size());
repi(i, SZ<int>(a)) a_[i] = {ALL(a[i])};
vvc<char> b_ = top(a_);
vstr b(b_.size());
repi(i, SZ<int>(b)) b[i] = {ALL(b_[i])};
return b;
}
template <class T, class = void>
struct has_e0 : false_type {};
template <class T>
struct has_e0<T, void_t<decltype(T::e0())>> : true_type {};
template <class T>
inline constexpr bool has_e0_v = has_e0<T>::value;
template <class T>
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<S>)
return S::e0();
else
return {};
}
template <class I, class = decltype(declval<S>() * declval<I>())>
static constexpr S pow(const S &a, I k) { return a * k; }
};
template <class T, auto infty = nullptr>
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<T, infty>(); }
template <class I>
static constexpr S pow(const S &a, I k) { return k == 0 ? e() : a; }
};
template <class T, auto infty = nullptr>
struct MonoidMax
{
using S = T;
static constexpr S op(S a, S b) { return max(a, b); }
static constexpr S e() { return -resolved_infty<T, infty>(); }
template <class I>
static constexpr S pow(const S &a, I k) { return k == 0 ? e() : a; }
};
#line 1467
template <class T>
vc<T> cumlsum(const vc<T> &v, int left_index = 0)
;
#line 1509
constexpr array<pll, 4> DRULgrid = {{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}};
constexpr array<pll, 4> DRULplane = {{{0, -1}, {1, 0}, {0, 1}, {-1, 0}}};
template <class T>
struct is_random_access_iterator
{
static constexpr bool value = is_same_v<
typename iterator_traits<T>::iterator_category,
random_access_iterator_tag
>;
};
template <class T>
constexpr bool is_random_access_iterator_v = is_random_access_iterator<T>::value;
#line 1581
#define DEFAULT_COMP ranges::less
#line 1691
namespace internal
{
};
#line 1784
template <class T>
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 <class T, class Sequence>
vc<T> content(queue<T, Sequence> que)
{
vc<T> res;
while (!que.empty())
{
res.eb(que.front());
que.pop();
}
return res;
}
template <class T, class Sequence, class Compare>
vc<T> content(priority_queue<T, Sequence, Compare> pque)
{
vc<T> res;
while (!pque.empty())
{
res.eb(pque.top());
pque.pop();
}
return res;
}
template <class T>
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 <class T>
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 <class U>
__attribute__((always_inline)) inline void read_wide_integer_tail(
U &value, const char *&p, uint64_t columns, uint64_t stop)
;
#line 2102
template <class T>
__attribute__((always_inline)) inline void rd1_integer(T &x)
{
using U = integer_magnitude<T>;
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<T>::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<T>::is_signed)
{
if (negative && value) x = T(-T(value - 1) - 1);
else x = T(value);
}
else x = T(value);
}
template <class T, enable_if_t<numeric_limits<T>::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 <class T>
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<T, float>) x = strtof(token.c_str(), &end);
else if constexpr (is_same_v<T, double>) 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 <class A, class B> void rd1(pair<A, B> &x);
template <class... T> void rd1(tuple<T...> &x);
template <class T, size_t N> void rd1(array<T, N> &x);
template <class T> void rd1(vc<T> &x);
template <class A, class B>
void rd1(pair<A, B> &x) { rd1(x.first), rd1(x.second); }
template <class... T>
void rd1(tuple<T...> &x)
{
apply([](auto &...element) { (rd1(element), ...); }, x);
}
template <class T, size_t N>
void rd1(array<T, N> &x)
{
for (auto &element : x) rd1(element);
}
template <class T>
void rd1(vc<T> &x)
{
if constexpr (is_same_v<T, bool>)
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<array<char, 3>, 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 <class U>
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 <class U, bool newline>
__attribute__((always_inline)) inline void write_wide_integer(U magnitude, bool negative)
;
#line 2410
template <class T, bool newline = false>
__attribute__((always_inline)) inline void wt1_integer(T x)
{
using U = integer_magnitude<T>;
U magnitude = U(x);
bool negative = false;
if constexpr (numeric_limits<T>::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<U, newline>(magnitude, negative);
}
template <class T, enable_if_t<numeric_limits<T>::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 <class T>
void wt1_real(T x)
{
char text[numeric_limits<T>::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 <class A, class B> void wt1(const pair<A, B> &x);
template <class... T> void wt1(const tuple<T...> &x);
template <class T, size_t N> void wt1(const array<T, N> &x);
template <class T> void wt1(const vc<T> &x);
template <class A, class B>
void wt1(const pair<A, B> &x) { wt1(x.first), append_char(' '), wt1(x.second); }
template <class... T>
void wt1(const tuple<T...> &x)
{
apply([](const auto &...element)
{
size_t index = 0;
((index++ ? void(append_char(' ')) : void(), wt1(element)), ...);
}, x);
}
template <class T, size_t N>
void wt1(const array<T, N> &x)
{
for (size_t i = 0; i < N; ++i)
{
if (i) append_char(' ');
wt1(x[i]);
}
}
template <class T>
void wt1(const vc<T> &x)
{
for (size_t i = 0; i < x.size(); ++i)
{
if (i) append_char(' ');
wt1(x[i]);
}
}
template <class... T>
void read(T &...x) { (rd1(x), ...); }
template <class... T>
void write(T &&...x) { (wt1(forward<T>(x)), ...); }
template <class... T>
void print(T &&...x)
{
if constexpr (sizeof...(T) == 1 &&
((is_integral_v<decay_t<T>> && !is_same_v<decay_t<T>, char>) && ...))
(wt1_integer<decay_t<T>, true>(forward<T>(x)), ...);
else
{
size_t index = 0;
((index++ ? void(append_char(' ')) : void(), wt1(forward<T>(x))), ...);
append_char('\n');
}
}
}
struct Dummy {
Dummy() { atexit(fastio::flush); }
} dummy;
//! https://trap.jp/post/1224/
#line 2556
namespace internal
{
template <class... Ts>
void READnodump(Ts &...a) { fastio::read(a...); }
#line 2586
template <class... T>
void READJAGnodump(int n, vvc<T> &...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<LIBRARY_INOUT_TYPE(T)> __VA_ARGS__; READJAG(n, __VA_ARGS__)
#line 2713
#define PRINT fastio::print
#line 2728
template <class T, class Add>
void offset(vc<T> &v, const Add &add) { for (auto &vi : v) vi += add; }
template <class T, class Add>
void offset(vvc<T> &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 <class T = ll, class U1, class U2>
T randrange(U1 l, U2 r)
{
assert(T(l) < T(r));
return uniform_int_distribution<T>(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 <class T>
[[deprecated("larger_int: 128-bit integer is not widened; intermediate arithmetic may overflow")]]
constexpr bool warn_no_wider_integer()
{
return true;
}
}
template <class T>
struct larger_int
{
private:
static constexpr bool check()
;
static_assert(check());
public:
using type = T;
};
#define LARGER_INT(T, U) \
template <> \
struct larger_int<T> \
{ \
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 <class T>
struct Rational;
template <class T>
struct larger_int<Rational<T>>
{
using type = Rational<typename larger_int<T>::type>;
};
template <class T>
using larger_int_t = typename larger_int<T>::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 <class T>
constexpr ll powmod_constexpr(ll x, ll n, T m)
{
if (m == 1)
return 0;
using U = make_unsigned_t<T>;
using L = larger_int_t<U>;
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 <class T>
constexpr bool isprime_constexpr(T n)
{
if constexpr (sizeof(T) > 4)
{
if (n <= INT_MAX)
return isprime_constexpr<int>(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<T>;
using L = larger_int_t<U>;
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 <auto n>
constexpr bool isprime = isprime_constexpr(n);
};
namespace internal
{
template <auto M>
struct policy_static
{
using mod_type = decltype(M);
using value_type = make_unsigned_t<mod_type>;
using calc_type = conditional_t<(M <= UINT_MAX), ull, larger_int_t<value_type>>;
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 <int id>
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 <int id>
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 <int id>
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 <cassert>
#include <string_view>
#include <type_traits>
namespace internal
{
template <class S>
inline constexpr bool is_modint_decimal_input =
std::is_convertible_v<const S &, std::string_view> &&
!std::is_same_v<std::decay_t<S>, decltype(nullptr)>;
template <class F>
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 <class T = ll>
constexpr tuple<T, T, T> extgcd(T a, T b)
;
#line 3365
namespace internal
{
template <class Policy, class PowInv = void>
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 <class T, typename = enable_if_t<is_integral_ext<T>>>
modint_impl(T v)
{
const V m = mod();
V rem;
if constexpr (is_signed_ext<T>)
{
using S = make_signed_t<V>;
S x = v % S(m);
if (x < 0)
x += m;
rem = x;
}
else
rem = V(v % m);
_v = Policy::init(rem);
};
template <class S, enable_if_t<is_modint_decimal_input<S>, 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<PowInv>)
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 <class T>
mint pow(T n) const
{
assert(n >= 0);
if constexpr (!is_void_v<PowInv>)
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<PowInv>)
{
return raw(PowInv::get().inv(val()));
}
else if constexpr (Policy::is_prime)
{
return pow(mod() - 2);
}
else
{
auto [g, x, y] = extgcd<M>(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 <int mod>
using static_modint32 = internal::modint_impl<internal::policy_static<mod>>;
template <int id>
using dynamic_modint32 = internal::modint_impl<internal::policy_barrett32<id>>;
template <ll mod>
using static_modint64 = internal::modint_impl<internal::policy_static<mod>>;
template <int id>
using dynamic_modint64_odd = internal::modint_impl<internal::policy_montgomery64_odd<id>>;
template <int id>
using dynamic_modint64 = internal::modint_impl<internal::policy_montgomery64<id>>;
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 <class T>
struct is_modint : std::false_type
{
};
template <class Policy, class PowInv>
struct is_modint<internal::modint_impl<Policy, PowInv>> : std::true_type
{
};
template <class T>
inline constexpr bool is_modint_v = is_modint<T>::value;
template <class T>
struct is_static_modint : false_type {};
template <int m, class PowInv>
struct is_static_modint<internal::modint_impl<internal::policy_static<m>, PowInv>> : true_type {};
template <ll m, class PowInv>
struct is_static_modint<internal::modint_impl<internal::policy_static<m>, PowInv>> : true_type {};
template <class T>
inline constexpr bool is_static_modint_v = is_static_modint<T>::value;
template <class T>
struct is_dynamic_modint : false_type {};
template <int id>
struct is_dynamic_modint<dynamic_modint32<id>> : true_type {};
template <int id>
struct is_dynamic_modint<dynamic_modint64_odd<id>> : true_type {};
template <int id>
struct is_dynamic_modint<dynamic_modint64<id>> : true_type {};
template <class T>
inline constexpr bool is_dynamic_modint_v = is_dynamic_modint<T>::value;
template <typename, typename = void>
struct has_mod : std::false_type
{
};
template <typename T>
struct has_mod<T, std::void_t<decltype(T::mod())>> : std::true_type
{
};
template <class mint>
struct modint_less
{
bool operator()(const mint &a, const mint &b) const
{
if constexpr (is_modint_v<mint>)
return a.val() < b.val();
else
return a < b;
}
};
template <class mint>
struct modint_hash
{
auto operator()(const mint &x) const
{
if constexpr (is_modint_v<mint>)
return std::hash<decltype(x.val())>{}(x.val());
else
return std::hash<mint>{}(x);
}
};
template <class mint>
struct PowerTable
{
private:
decltype(mint::mod()) mod{};
mint base{};
vc<mint> 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 <class T>
struct Binomial
{
private:
inline static decltype(T::mod()) mod;
public:
inline static vc<T> fac_, finv_, inv_;
static void reserve(int n)
{
if constexpr (is_dynamic_modint_v<T>)
{
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 <class T = ll, class U = larger_int_t<T>>
pair<T, T> svp2d(const pair<T, T> &a, const pair<T, T> &b)
;
#line 3846
template <class mint>
pair<decltype(mint(0).val()), decltype(mint(0).val())>
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 <class T>
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 <class T>
requires requires(const T &x)
{
{ T::mod() } -> std::convertible_to<ll>;
{ x.val() } -> std::convertible_to<ll>;
}
constexpr auto operator()(const T &x) const
-> rat_value<typename decltype(mint_to_rat(x))::first_type>
{
auto [p, q] = mint_to_rat(x);
return {p, q};
}
};
template <class T>
struct rat_object
{
T value;
};
template <class T>
inline constexpr bool rat_is_map =
false;
template <class... Args>
inline constexpr bool rat_is_map<std::map<Args...>> = true;
template <class... Args>
inline constexpr bool rat_is_map<std::multimap<Args...>> = true;
template <class... Args>
inline constexpr bool rat_is_map<std::unordered_map<Args...>> = true;
template <class... Args>
inline constexpr bool rat_is_map<std::unordered_multimap<Args...>> = true;
struct rat_closure : std::ranges::range_adaptor_closure<rat_closure>
{
template <class T>
static constexpr bool can_convert()
;
#line 3948
template <typename T>
requires(!requires { std::views::all | std::declval<T>(); })
constexpr decltype(auto) operator()(T &&t) const
{
if constexpr (!std::ranges::range<T> && std::invocable<mint_to_rat_fn, T>)
{
return mint_to_rat_fn{}(std::forward<T>(t));
}
else if constexpr (can_convert<T>())
{
if constexpr (!std::ranges::range<T> || rat_is_map<std::remove_cvref_t<T>>)
return rat_object<T>{std::forward<T>(t)};
else
return std::forward<T>(t) | std::views::transform(*this);
}
else
{
return std::forward<T>(t);
}
}
};
#line 4022
template <typename T>
requires(!requires { std::views::all | std::declval<T>(); })
constexpr decltype(auto) operator|(T &&t, rat_closure c)
{
return c(std::forward<T>(t));
}
}
using mint = modint998244353;
// using mint = modint1000000007;
// using mint = static_modint<1000000000>;
// using mint = modint;
using bi = Binomial<mint>;
void init()
{
oj(mt.seed(random_device()()));
}
#line 4064
namespace internal_monoid_power
{
template <class T, class I, class = void>
struct HasMemberScalarProduct : false_type {};
template <class T, class I>
struct HasMemberScalarProduct<T, I, void_t<decltype(T(declval<const T &>().operator*({declval<I>()})))>> : true_type {};
template <class T, class I, class = void>
struct HasFreeScalarProduct : false_type {};
template <class T, class I>
struct HasFreeScalarProduct<T, I, void_t<decltype(T(operator*(declval<const T &>(), {declval<I>()})))>> : true_type {};
template <class T, class I>
struct HasScalarProduct : bool_constant<is_arithmetic_v<T> || is_same_v<T, f128> ||
HasMemberScalarProduct<T, I>::value || HasFreeScalarProduct<T, I>::value> {};
template <class T, class I>
constexpr T scale(const T &x, I k)
;
#line 4138
template <class M, class I>
using ConstRefPower = typename M::S (*)(const typename M::S &, I);
template <class M, class I>
using ValuePower = typename M::S (*)(typename M::S, I);
template <class M, class I, class = void>
struct HasConstRefPower : false_type {};
template <class M, class I>
struct HasConstRefPower<M, I, void_t<decltype(static_cast<ConstRefPower<M, I>>(M::pow))>> : true_type {};
template <class M, class I, class = void>
struct HasValuePower : false_type {};
template <class M, class I>
struct HasValuePower<M, I, void_t<decltype(static_cast<ValuePower<M, I>>(M::pow))>> : true_type {};
template <class M, class I>
constexpr typename M::S power(const typename M::S &x, I k)
;
}
template <class S_, auto op_, auto e_>
struct Monoid
{
using S = S_;
static constexpr auto op = op_;
static constexpr auto e = e_;
};
template <class S_, auto op_, auto e_, auto inv_>
struct Group
{
using S = S_;
static constexpr auto op = op_;
static constexpr auto e = e_;
static constexpr auto inv = inv_;
};
template <class S_, auto add_, auto e0_, auto mul_, auto e1_>
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 <class S_, auto add_, auto e0_, auto minus_, auto mul_, auto e1_>
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 <class S_, auto add_, auto e0_, auto minus_, auto mul_, auto e1_, auto inv_>
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 <class M, class = void>
struct HasInverse : false_type {};
template <class M>
struct HasInverse<M, void_t<decltype(M::inv(declval<const typename M::S &>()))>> : true_type {};
template <class M>
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 <class I>
static constexpr S pow(const S &x, I k) { return internal_monoid_power::power<M>(x, k); }
};
template <class G>
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 <class I>
static constexpr S pow(const S &x, I k) { return internal_monoid_power::power<G>(x, k); }
};
template <class M>
struct NormalAndOppositeMonoid
{
struct S
{
typename M::S normal;
typename M::S opposite;
S() {}
template <class... Args,
std::enable_if_t<std::is_constructible_v<typename M::S, Args...>, std::nullptr_t> = nullptr>
S(Args &&...args)
: normal(std::forward<Args>(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 <class I>
static constexpr S pow(const S &x, I k) { return {internal_monoid_power::power<M>(x.normal, k), internal_monoid_power::power<M>(x.opposite, k)}; }
};
template <class G>
struct NormalAndOppositeGroup
{
struct S
{
typename G::S normal;
typename G::S opposite;
S() {}
template <class... Args,
std::enable_if_t<std::is_constructible_v<typename G::S, Args...>, std::nullptr_t> = nullptr>
S(Args &&...args)
: normal(std::forward<Args>(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 <class I>
static constexpr S pow(const S &x, I k) { return {internal_monoid_power::power<G>(x.normal, k), internal_monoid_power::power<G>(x.opposite, k)}; }
};
template <class SR>
using MonoidOfSemiRingAdd = Monoid<typename SR::S, SR::add, SR::e0>;
template <class SR>
using MonoidOfSemiRingMul = Monoid<typename SR::S, SR::mul, SR::e1>;
template <class R>
using GroupOfRingAdd = Group<typename R::S, R::add, R::e0, R::minus>;
template <class K>
using GroupOfFieldMul = Group<typename K::S, K::mul, K::e1, K::inv>;
template <class Madd, class Mmul>
struct SemiRingFromMonoidMonoid
{
static_assert(is_same_v<typename Madd::S, typename Mmul::S>, "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 <class Gadd, class Mmul>
struct RingFromGroupMonoid
{
static_assert(is_same_v<typename Gadd::S, typename Mmul::S>, "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 <class Gadd, class Gmul>
struct FieldFromGroupGroup
{
static_assert(is_same_v<typename Gadd::S, typename Gmul::S>, "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 <class T, class = void>
struct has_e1 : false_type {};
template <class T>
struct has_e1<T, void_t<decltype(T::e1())>> : true_type {};
template <class T>
inline constexpr bool has_e1_v = has_e1<T>::value;
template <class T>
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<S>)
return S::e1();
else
return S(1);
}
};
template <class T>
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<S>)
return S::e0();
else
return S{};
}
static constexpr S inv(S a) { return -a; }
template <class I, class = decltype(declval<S>() * declval<I>())>
static constexpr S pow(const S &a, I k) { return a * k; }
};
template <class T>
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<S>)
return S::e1();
else
return S(1);
}
static constexpr S inv(S a) { return e() / a; }
};
template <class T, auto infty = nullptr>
using SemiRingMinPlus = SemiRingFromMonoidMonoid<MonoidMin<T, infty>, MonoidAdd<T>>;
template <class T, auto infty = nullptr>
using SemiRingMaxPlus = SemiRingFromMonoidMonoid<MonoidMax<T, infty>, MonoidAdd<T>>;
template <class T>
using RingAddSubMul = RingFromGroupMonoid<GroupAddSub<T>, MonoidMul<T>>;
template <class T>
using FieldAddSubMulDiv = FieldFromGroupGroup<GroupAddSub<T>, GroupMulDiv<T>>;
#line 4415
namespace internal
{
template <class S>
struct ordinary_mod32 : false_type {};
template <int mod, class PowInv>
struct ordinary_mod32<modint_impl<policy_static<mod>, PowInv>> : true_type {};
template <int id>
struct ordinary_mod32<dynamic_modint32<id>> : true_type {};
}
namespace internal
{
template <class G>
struct ordinary_mod32_add_group : false_type {};
template <class S>
struct ordinary_mod32_add_group<GroupAddSub<S>> : ordinary_mod32<S> {};
template <class S>
struct ordinary_mod32_add_group<Group<S, GroupAddSub<S>::op, GroupAddSub<S>::e, GroupAddSub<S>::inv>>
: ordinary_mod32<S> {};
template <class F>
struct ordinary_mod32_field : false_type {};
template <class S>
struct ordinary_mod32_field<FieldAddSubMulDiv<S>> : ordinary_mod32<S> {};
}
#include <algorithm>
#include <cstddef>
#include <cstdint>
namespace internal
{
template <class NextProduct>
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<std::uint32_t>(carry);
}
}
namespace internal
{
template <class S>
using dot_product_mod32_value = ordinary_mod32<S>;
template <int block, class S, class It1, class It2>
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 <class S, class It1, class It2>
S dot_product_mod32_values(int n, It1 a, It2 b)
{
static_assert(ordinary_mod32<S>::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 <class SR>
struct dot_product_mod32 : false_type {};
template <class S>
struct dot_product_mod32<FieldAddSubMulDiv<S>> : dot_product_mod32_value<S> {};
template <class S>
struct dot_product_mod32<RingAddSubMul<S>> : dot_product_mod32_value<S> {};
template <class S>
struct dot_product_mod32<SemiRingFromMonoidMonoid<MonoidAdd<S>, MonoidMul<S>>>
: dot_product_mod32_value<S> {};
}
template <class SR, class It1, class It2>
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<SR>::value)
{
return internal::dot_product_mod32_values<S>(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 <class F>
struct BerlekampMassey
{
using S = typename F::S;
vc<S> 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<F>(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<S> coefficients() const
{
vc<S> res;
res.reserve(c.size() + 1);
res.eb(F::minus(F::e1()));
res.insert(res.end(), c.begin(), c.end());
return res;
}
};
template <class F>
vc<typename F::S> berlekamp_massey(const vc<typename F::S> &a)
{
BerlekampMassey<F> bm;
bm.a.reserve(a.size());
for (const auto &x : a) bm.append(x);
return bm.coefficients();
}
template <class mint = modint998244353, bool nonzero = false>
mint random_modint()
{
return mint(randrange<ull>(nonzero ? 1 : 0, mint::mod()));
}
//! https://yukicoder.me/wiki/black_box_linear_algebra
namespace bbla
{
template <class mint>
mint random_sample_mint() ;
template <class F, class LinearMap>
vc<typename F::S> krylov_sequence(const LinearMap &linear_map, const vc<typename F::S> &u,
vc<typename F::S> v, int count)
{
using S = typename F::S;
assert(count >= 0 && u.size() == v.size());
vc<S> a(count, F::e0());
repi(i, count)
{
a[i] = dot_product<F>(u.size(), u.begin(), v.begin());
if (i + 1 < count) linear_map(v);
}
return a;
}
#line 4703
template <class F, class LinearMap, class RandomSample = decltype(random_sample_mint<typename F::S>)>
vc<typename F::S> minimal_polynomial(int n, const LinearMap &linear_map, const RandomSample &random_sample = random_sample_mint)
{
using S = typename F::S;
assert(n >= 0);
vc<S> u(n, F::e0()), v(n, F::e0());
repi(j, n) u[j] = random_sample(), v[j] = random_sample();
return reversed(berlekamp_massey<F>(krylov_sequence<F>(linear_map, u, move(v), 2 * n)));
}
#line 4792
}
template <class T, bool is_erasable = false>
struct CSR
{
protected:
int n, m;
vc<int> start;
vc<T> elist;
vc<int> len;
inline int get_last(int i) const
{
if constexpr (is_erasable)
return start[i] + len[i];
else
return start[i + 1];
}
template <class Iter>
struct RowBase
{
using iterator = Iter;
using reference = typename iterator_traits<iterator>::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 <class I = ll>
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<T> content() const ;
};
using Row = RowBase<typename vc<T>::iterator>;
using ConstRow = RowBase<typename vc<T>::const_iterator>;
public:
CSR() : n(0), m(0), start{0} {}
template <class I = int>
CSR(const vc<I> &row_sizes)
: n(row_sizes.size())
{
static_assert(is_integral_ext<I>);
start.resize(n + 1);
for (int i = 0; i < n; i++)
{
if constexpr (is_signed_ext<I>) 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 <class I>
CSR(int n, const vc<pair<I, T>> &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 <class U = T>
CSR(const vvc<U> &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 <class U, bool erasable>
explicit CSR(const CSR<U, erasable> &other)
: CSR(gen_vec(other.template size<int>(), [&](int i) { return other[i].template size<int>(); }))
{
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 <class I = ll>
I size() const { return n; }
vvc<T> content() const ;
vc<T> &get_elist() { return elist; }
const vc<T> &get_elist() const { return elist; }
};
template <class T>
CSR(const vvc<T> &) -> CSR<T>;
namespace internal
{
template <class S, class Rows>
pair<int, S> 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<ull> w(n, vc<ull>(m));
vc<int> used(n);
vc<int> 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 <cassert>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <type_traits>
#include <utility>
#include <vector>
namespace internal { namespace matrix_power_mod32_detail {
template <class T>
inline constexpr bool supported_builtin_exponent_v =
std::is_integral_v<T>
|| std::is_same_v<T, __int128> || std::is_same_v<T, unsigned __int128>
;
template <class S>
using Matrix = std::vector<std::vector<S>>;
#line 5145
template <class T>
std::size_t binary_multiplication_count(T exponent) ;
#line 5436
template <class S, class T>
Matrix<S> power_over_field(const Matrix<S>& a, T exponent) ;
#line 5495
template <class S>
bool is_prime_modulus() ;
#line 5510
} }
namespace internal
{
template <class Iterator> struct matrix_row
{
using value_type = typename iterator_traits<Iterator>::value_type;
using reference = typename iterator_traits<Iterator>::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<value_type>() 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 <class Range> matrix_row &operator=(const Range &b)
{
assert(size() == b.size());
copy(b.begin(), b.end(), first);
return *this;
}
matrix_row &operator=(initializer_list<value_type> b)
{
assert(size() == b.size());
copy(b.begin(), b.end(), first);
return *this;
}
template <class Range> bool operator==(const Range &b) const
{
return size() == b.size() && equal(first, last, b.begin());
}
template <class Range> bool operator!=(const Range &b) const { return !(*this == b); }
};
template <class T, class A, class It>
bool operator==(const vector<T, A> &a, const matrix_row<It> &b)
{
return b == a;
}
template <class T, size_t N, class It>
bool operator==(const array<T, N> &a, const matrix_row<It> &b)
{
return b == a;
}
template <class Owner> struct matrix_row_iterator
{
using value_type = decltype(declval<Owner &>()[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 <class T> struct matrix_storage
{
using reference = typename vc<T>::reference;
using const_reference = typename vc<T>::const_reference;
private:
int rows_ = 0, columns_ = 0;
vc<T> 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<T> &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 <class I = ll> pair<I, I> 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<decltype(b)>{b, b + columns_};
}
auto row(int i) const
{
auto b = values_.begin() + size_t(i) * columns_;
return matrix_row<decltype(b)>{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<matrix_storage>{this, 0}; }
auto end() { return matrix_row_iterator<matrix_storage>{this, rows_}; }
auto begin() const { return matrix_row_iterator<const matrix_storage>{this, 0}; }
auto end() const { return matrix_row_iterator<const matrix_storage>{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<T> &content() const ;
template <class U = T> vvc<U> to_vvi() const
;
operator vvc<T>() 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 <class F, int BS, class A, class B, class C>
void matrix_product(int n, int m, int p, const A &a, const B &b, C &c)
;
#line 5855
}
template <class F, int BS = 32>
struct Matrix : internal::matrix_storage<typename F::S>
{
using S = typename F::S;
using M = Matrix;
using V = vc<S>;
using Base = internal::matrix_storage<S>;
template<class I=ll> pair<I,I> shape() const { return Base::template shape<I>(); }
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<S> &a) : Base(a) {}
Matrix(initializer_list<V> a) : Matrix(vvc<S>(a)) {}
M transpose() const
{
auto [n, m] = shape<int>();
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<int>();
assert(0 <= j && j < m);
return gen_vec(n, [&](int i) -> S { return (*this)[i][j]; });
}
template <class I = int>
M select_rows(const vc<I> &indices) const
{
static_assert(is_integral_ext<I>);
auto [n, m] = shape<int>();
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<int>();
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<int>() == b.shape<int>());
auto [n, m] = shape<int>();
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<int>() == b.shape<int>());
auto [n, m] = shape<int>();
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<int>();
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<int>();
assert(SZ(v) == m);
V res(n, F::e0());
repi(i, n) res[i] = dot_product<F>(m, (*this)[i].begin(), v.begin());
return res;
}
friend V operator*(const V &v, const M &a)
{
auto [n, m] = a.template shape<int>();
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<int>();
auto [m_, p] = b.shape<int>();
assert(m == m_);
M res(n, p);
internal::matrix_product<F, BS>(n, m, p, *this, b, res);
return res;
}
template <class T = ll>
M pow(T k) const
{
auto [n, m] = shape<int>();
assert(n == m);
if (n == 0) return M(n, n, F::e1());
if constexpr (internal::ordinary_mod32_field<F>::value &&
internal::matrix_power_mod32_detail::supported_builtin_exponent_v<T>)
{
if (n >= 24 && k > 0 && internal::matrix_power_mod32_detail::binary_multiplication_count(k) > 10 &&
internal::matrix_power_mod32_detail::is_prime_modulus<S>())
{
const vvc<S> &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 <class I = ll>
tuple<M, I, S> row_reduction(bool rref = false) const
{
auto [n, m] = shape<int>();
M a(*this);
if constexpr (internal::ordinary_mod32_field<F>::value)
{
if (n >= 32 && m >= 32)
{
auto [rk, de] = internal::row_reduction_mod32<S>(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 <class I = ll>
I rank() const { return get<1>(row_reduction()); }
#line 6174
optional<M> inv() const
{
auto [n, m] = shape<int>();
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 <class Tag>
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<void>
{
using Type = monostate;
explicit BasisTag(monostate = {}) {}
bool accepts(const monostate *) const { return true; }
};
}
template <class F, bool Restore = false, class Tag = int>
class LinearBasis
{
template <class, bool, class> friend class LinearBasis;
using TagData = internal::BasisTag<Tag>;
using StoredTag = typename TagData::Type;
static constexpr bool tagged = !is_void_v<Tag>;
public:
using S = typename F::S;
using TagType = Tag;
private:
using Coefficient = conditional_t<Restore, vc<S>, monostate>;
struct Row : TagData
{
int pivot;
vc<S> value;
Coefficient coefficient;
#line 6285
Row(int pivot, vc<S> 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<Row> rows_;
vvc<S> original_;
static void scale(vc<S> &value, const S &factor)
;
vc<S> eliminate(vc<S> value, vc<S> *coefficient, const StoredTag *threshold) const
;
#line 6328
template <bool UseTags>
bool insert_impl(const vc<S> &value, StoredTag tag)
;
#line 6381
public:
explicit LinearBasis(int dimension = 0) : dimension_(dimension) { assert(dimension >= 0); }
LinearBasis(int dimension, const vvc<S> &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<S> &value)
{
if constexpr (tagged)
{
if constexpr (!is_trivially_default_constructible_v<StoredTag>) return insert(value, StoredTag{});
else if (use_tags_) return insert_impl<true>(value, StoredTag{});
}
return insert_impl<false>(value, StoredTag{});
}
vc<S> reduce(const vc<S> &value) const { return eliminate(value, nullptr, nullptr); }
template <bool Enabled = tagged, enable_if_t<Enabled && tagged, int> = 0>
bool insert(const vc<S> &value, StoredTag tag)
{
use_tags_ = true;
return insert_impl<true>(value, std::move(tag));
}
template <bool Enabled = tagged, enable_if_t<Enabled && tagged, int> = 0>
int rank(const StoredTag &threshold) const
{
int result = 0;
for (const auto &row : rows_) if (row.accepts(&threshold)) result++;
return result;
}
template <bool Enabled = tagged, enable_if_t<Enabled && tagged, int> = 0>
vc<S> reduce(const vc<S> &value, const StoredTag &threshold) const { return eliminate(value, nullptr, &threshold); }
#line 6445
template <bool OtherRestore>
void merge(const LinearBasis<F, OtherRestore, Tag> &other)
;
#line 6463
template <bool OtherRestore>
LinearBasis intersection(const LinearBasis<F, OtherRestore, Tag> &other) const
;
#line 6501
template <bool OtherRestore>
LinearBasis operator|(const LinearBasis<F, OtherRestore, Tag> &other) const
{
auto result = *this;
result.merge(other);
return result;
}
template <bool OtherRestore>
LinearBasis operator&(const LinearBasis<F, OtherRestore, Tag> &other) const { return intersection(other); }
};
namespace bbla
{
namespace detail
{
template <class F, class RandomSample>
vc<typename F::S> random_diagonal(int n, const RandomSample &sample)
{
vc<typename F::S> d(n);
for (auto &x : d) do { x = sample(); } while (x == F::e0());
return d;
}
template <class F>
void scale_diagonal(vc<typename F::S> &v, const vc<typename F::S> &d)
{
assert(v.size() == d.size());
repi(i, v.size()) v[i] = F::mul(v[i], d[i]);
}
#line 6558
}
template <class F, class LinearMap, class TransposeMap,
class RandomSample = decltype(random_sample_mint<typename F::S>)>
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<F>(rows, random_sample);
auto dc = detail::random_diagonal<F>(cols, random_sample);
auto gram = [&](vc<S> &v)
{
if (cols <= rows)
{
apply(v);
detail::scale_diagonal<F>(v, dr);
transpose(v);
detail::scale_diagonal<F>(v, dc);
}
else
{
transpose(v);
detail::scale_diagonal<F>(v, dc);
apply(v);
detail::scale_diagonal<F>(v, dr);
}
};
auto m = minimal_polynomial<F>(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 <class S>
struct LinearSolution
{
bool solvable;
vc<S> solution;
vc<S> 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 F = FieldAddSubMulDiv<modint998244353>>
class SparseMatrix
{
public:
using S = typename F::S;
using V = vc<S>;
using Entry = pair<int, S>;
private:
int n_ = 0, m_ = 0;
CSR<Entry> rows_;
static CSR<Entry> canonical_rows(CSR<Entry> rows)
{
const int n = rows.template size<int>();
vc<int> 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<Entry> 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<Entry>(vc<int>(n));
}
template <class I = int, class J = int>
SparseMatrix(int n, int m, const vc<tuple<I, J, S>> &entries) : SparseMatrix(n, m)
{
static_assert(is_integral_ext<I> && is_integral_ext<J>);
vc<int> sizes(n);
for (const auto &[i, j, x] : entries)
{
assert(u128(i) < unsigned(n) && u128(j) < unsigned(m));
sizes[int(i)]++;
}
CSR<Entry> 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<tuple<int, int, S>> entries)
: SparseMatrix(n, m, vc<tuple<int, int, S>>(entries)) {}
template <class I, bool Erasable>
SparseMatrix(int columns, const CSR<pair<I, S>, Erasable> &rows)
: SparseMatrix(rows.template size<int>(), columns)
{
static_assert(is_integral_ext<I>);
vc<int> sizes(n_);
for (int i = 0; i < n_; i++) sizes[i] = rows[i].template size<int>();
CSR<Entry> 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 <int BS>
explicit SparseMatrix(const Matrix<F, BS> &matrix)
{
tie(n_, m_) = matrix.template shape<int>();
vc<tuple<int, int, S>> 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 <class I = ll> pair<I, I> shape() const { return {n_, m_}; }
template <class I = ll> I size() const { return n_; }
template <class I = ll> I nnz() const { return rows_.get_elist().size(); }
auto operator[](int i) const { assert(0 <= i && i < n_); return rows_[i]; }
const CSR<Entry> &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<F> to_dense() const
;
SparseMatrix transpose() const
{
vc<int> sizes(m_);
for (const auto &[j, x] : rows_.get_elist()) sizes[j]++;
SparseMatrix result(m_, n_);
result.rows_ = CSR<Entry>(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 <class I = int>
SparseMatrix select_rows(const vc<I> &indices) const
{
static_assert(is_integral_ext<I>);
vc<int> 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<int>();
}
SparseMatrix result(indices.size(), m_);
result.rows_ = CSR<Entry>(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 <int BS>
Matrix<F, BS> operator*(const Matrix<F, BS> &b) const
{
const auto [m, p] = b.template shape<int>();
assert(m_ == m);
Matrix<F, BS> 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 <int BS>
friend Matrix<F, BS> operator*(const Matrix<F, BS> &a, const SparseMatrix &b)
{
const auto [n, m] = a.template shape<int>();
assert(m == b.n_);
Matrix<F, BS> 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<F> multiply_dense(const SparseMatrix &b) const
{
assert(m_ == b.n_);
Matrix<F> 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<int> seen(b.m_, -1), touched;
vc<tuple<int, int, S>> 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 <class I = ll, class Sample = decltype(bbla::random_sample_mint<S>) &>
I rank(int trials = 2, Sample &&sample = bbla::random_sample_mint<S>) const
{
assert(trials > 0);
if (n_ == 0 || m_ == 0 || nnz<u128>() == 0) return I(0);
if (internal::prefer_dense_rank(n_, m_, u128(n_) * m_ + nnz<u128>(), nnz<u128>(), trials))
return to_dense().template rank<I>();
auto apply = [&](V &v) { v = *this * v; };
auto transpose_apply = [&](V &v) { v = v * *this; };
auto random = [&]() -> S { return sample(); };
return I(bbla::rank<F>(n_, m_, apply, transpose_apply, trials, random));
}
#line 7009
};
template <class F = FieldAddSubMulDiv<modint998244353>>
class LinearMatroid
{
public:
using S = typename F::S;
private:
int dimension_ = 0;
vvc<S> columns_;
vc<int> selected_;
vc<unsigned char> used_;
LinearBasis<F, true, void> basis_;
public:
LinearMatroid() = default;
LinearMatroid(int dimension, const vvc<S> &columns)
: LinearMatroid(dimension, vvc<S>(columns)) {}
LinearMatroid(int dimension, vvc<S> &&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 <int BS>
explicit LinearMatroid(const Matrix<F, BS> &matrix)
: LinearMatroid(matrix.template shape<int>().first,
gen_vec(matrix.template shape<int>().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<S> &columns() const ;
Matrix<F> matrix() const
{
Matrix<F> 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 <class I = int>
void build(const vc<I> &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 F, bool Sparse>
class LinearRepresentationBuilder
{
using S = typename F::S;
int dimension_, size_;
conditional_t<Sparse, vc<tuple<int, int, S>>, Matrix<F>> data_;
public:
LinearRepresentationBuilder(int dimension, int size)
: dimension_(dimension), size_(size), data_([&]
{
if constexpr (Sparse) return vc<tuple<int, int, S>>{};
else return Matrix<F>(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<F>(dimension_, size_, data_);
else return std::move(data_);
}
};
}
namespace internal::linear_matroid_detail
{
template <class F, int BS>
int element_count(const Matrix<F, BS> &matrix)
;
template <class F>
int element_count(const LinearMatroid<F> &matroid)
;
template <class F, int BS>
vvc<typename F::S> compressed_columns(const Matrix<F, BS> &matrix)
;
template <class F>
vvc<typename F::S> compressed_columns(const LinearMatroid<F> &matroid)
;
template <class F, class M, class I, class J>
pair<vvc<typename F::S>, vc<pair<int, int>>>
parity_representation(const M &matroid, const vc<pair<I, J>> &pairs)
{
const int n = element_count(matroid);
vc<unsigned char> 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<typename F::S> columns;
vc<pair<int, int>> 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<pair<int, int>> consecutive_pairs(int size)
{
assert(size % 2 == 0);
vc<pair<int, int>> 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 <class F, class Sample>
int sparse_intersection_rank(const SparseMatrix<F> &a, const SparseMatrix<F> &b,
const vc<unsigned char> &active, Sample &sample)
;
#line 7291
template <class I, class J>
vc<pair<int, int>> sparse_parity_pairs(int size, const vc<pair<I, J>> &pairs)
{
static_assert(is_integral_ext<I> && is_integral_ext<J>);
vc<unsigned char> used(size);
vc<pair<int, int>> 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 <class F, class Sample>
int sparse_parity_rank(const SparseMatrix<F> &matrix, const vc<pair<int, int>> &pairs,
const vc<unsigned char> &active, Sample &sample)
{
using S = typename F::S;
const auto shape = matrix.template shape<int>();
const int d = shape.first, n = shape.second, m = pairs.size();
if (!d || !m) return 0;
vc<S> diagonal(m, F::e0());
for (int e = 0; e < m; e++) if (active[e]) diagonal[e] = sample();
auto apply = [&](vc<S> &v)
{
auto middle = v * matrix;
vc<S> 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<S> &v)
{
apply(v);
for (auto &x : v) x = F::minus(x);
};
auto random = [&]() -> S { return sample(); };
return bbla::rank<F>(d, d, apply, transpose, 1, random) / 2;
}
template <class F>
optional<SparseMatrix<F>> compact_nonzero_rows(const SparseMatrix<F> &matrix)
{
const int d = matrix.template shape<int>().first;
vc<int> 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 F>
class SparseIntersectionRank
{
using S = typename F::S;
const SparseMatrix<F> &original_a_, &original_b_;
optional<SparseMatrix<F>> compact_a_, compact_b_, transpose_b_;
const SparseMatrix<F> &a() const { return compact_a_ ? *compact_a_ : original_a_; }
const SparseMatrix<F> &b() const { return compact_b_ ? *compact_b_ : original_b_; }
public:
bool dense;
SparseIntersectionRank(const SparseMatrix<F> &first, const SparseMatrix<F> &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<int>(), sb = b().template shape<int>();
const int n = sa.second;
assert(n == sb.second);
vc<int> 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<u128>() + b().template nnz<u128>();
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 <class Sample>
int operator()(const vc<unsigned char> &active, Sample &sample) const
{
const auto sa = a().template shape<int>(), sb = b().template shape<int>();
if (!sa.first || !sb.first || !sa.second) return 0;
if (!dense) return sparse_intersection_rank(a(), b(), active, sample);
vc<S> 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<int>();
}
};
template <class F>
class SparseParityRank
{
using S = typename F::S;
const SparseMatrix<F> &original_;
const vc<pair<int, int>> &pairs_;
optional<SparseMatrix<F>> compact_, transpose_;
u128 products_ = 0;
const SparseMatrix<F> &matrix() const { return compact_ ? *compact_ : original_; }
public:
bool dense;
SparseParityRank(const SparseMatrix<F> &representation, const vc<pair<int, int>> &pairs)
: original_(representation), pairs_(pairs), compact_(compact_nonzero_rows(representation))
{
const auto shape = matrix().template shape<int>();
vc<int> 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<u128>();
dense = internal::prefer_dense_rank(shape.first, shape.first,
shape.first + work + 2 * products_, work);
if (dense) transpose_.emplace(matrix().transpose());
}
template <class Sample>
int operator()(const vc<unsigned char> &active, Sample &sample) const
{
const int d = matrix().template shape<int>().first;
if (!d || products_ == 0) return 0;
if (!dense) return sparse_parity_rank(matrix(), pairs_, active, sample);
const int n = matrix().template shape<int>().second;
vc<tuple<int, int, S>> 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<F> alternating(n, n, entries);
int rank = matrix().multiply_dense(alternating * *transpose_).template rank<int>();
assert(rank % 2 == 0);
return rank / 2;
}
};
#line 7481
}
namespace internal::linear_matroid_detail
{
template <class F, class M, class I, class J, class Sample>
int dense_parity_size(const M &matroid, const vc<pair<I, J>> &pairs, Sample &sample, int trials)
;
#line 7531
}
template <class F, int BS, class Sample, class I = int, class J = int,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
int linear_matroid_parity_size(const Matrix<F, BS> &matroid,
const vc<pair<I, J>> &pairs,
Sample &&sample, int trials = 1)
{
return internal::linear_matroid_detail::dense_parity_size<F>(matroid, pairs, sample, trials);
}
template <class F, int BS, class Sample,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
int linear_matroid_parity_size(const Matrix<F, BS> &matroid,
Sample &&sample, int trials = 1)
{
const int n = matroid.template shape<int>().second;
auto pairs = internal::linear_matroid_detail::consecutive_pairs(n);
return linear_matroid_parity_size(matroid, pairs, std::forward<Sample>(sample), trials);
}
template <class F, int BS, class Sample, class I = int, class J = int,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
vc<int> linear_matroid_parity_restore(const Matrix<F, BS> &matroid,
const vc<pair<I, J>> &pairs,
Sample &&sample, int trials = 1)
;
template <class F, int BS, class Sample,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
vc<int> linear_matroid_parity_restore(const Matrix<F, BS> &matroid,
Sample &&sample, int trials = 1)
;
template <class F, int BS, class I = int, class J = int>
int linear_matroid_parity_size(const Matrix<F, BS> &matroid,
const vc<pair<I, J>> &pairs, int trials = 1)
{
return linear_matroid_parity_size(matroid, pairs, random_modint<typename F::S>, trials);
}
template <class F, int BS>
int linear_matroid_parity_size(const Matrix<F, BS> &matroid, int trials = 1)
{
return linear_matroid_parity_size(matroid, random_modint<typename F::S>, trials);
}
template <class F, int BS>
int linear_matroid_parity_size(const Matrix<F, BS> &matroid,
initializer_list<pair<int, int>> pairs, int trials = 1)
{
return linear_matroid_parity_size(matroid, vc<pair<int, int>>(pairs), trials);
}
template <class F, int BS, class I = int, class J = int>
vc<int> linear_matroid_parity_restore(const Matrix<F, BS> &matroid,
const vc<pair<I, J>> &pairs, int trials = 1)
;
template <class F, int BS>
vc<int> linear_matroid_parity_restore(const Matrix<F, BS> &matroid, int trials = 1)
;
template <class F, int BS>
vc<int> linear_matroid_parity_restore(const Matrix<F, BS> &matroid,
initializer_list<pair<int, int>> pairs, int trials = 1)
;
template <class F, class Sample, class I = int, class J = int,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
int linear_matroid_parity_size(const LinearMatroid<F> &matroid,
const vc<pair<I, J>> &pairs,
Sample &&sample, int trials = 1)
{
return internal::linear_matroid_detail::dense_parity_size<F>(matroid, pairs, sample, trials);
}
template <class F, class Sample,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
int linear_matroid_parity_size(const LinearMatroid<F> &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>(sample), trials);
}
template <class F, class Sample, class I = int, class J = int,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
vc<int> linear_matroid_parity_restore(const LinearMatroid<F> &matroid,
const vc<pair<I, J>> &pairs,
Sample &&sample, int trials = 1)
;
template <class F, class Sample,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
vc<int> linear_matroid_parity_restore(const LinearMatroid<F> &matroid,
Sample &&sample, int trials = 1)
;
template <class F, class I = int, class J = int>
int linear_matroid_parity_size(const LinearMatroid<F> &matroid,
const vc<pair<I, J>> &pairs, int trials = 1)
{
return linear_matroid_parity_size(matroid, pairs, random_modint<typename F::S>, trials);
}
template <class F>
int linear_matroid_parity_size(const LinearMatroid<F> &matroid, int trials = 1)
{
return linear_matroid_parity_size(matroid, random_modint<typename F::S>, trials);
}
template <class F>
int linear_matroid_parity_size(const LinearMatroid<F> &matroid,
initializer_list<pair<int, int>> pairs, int trials = 1)
{
return linear_matroid_parity_size(matroid, vc<pair<int, int>>(pairs), trials);
}
template <class F, class I = int, class J = int>
vc<int> linear_matroid_parity_restore(const LinearMatroid<F> &matroid,
const vc<pair<I, J>> &pairs, int trials = 1)
;
template <class F>
vc<int> linear_matroid_parity_restore(const LinearMatroid<F> &matroid, int trials = 1)
;
template <class F>
vc<int> linear_matroid_parity_restore(const LinearMatroid<F> &matroid,
initializer_list<pair<int, int>> pairs, int trials = 1)
;
template <class F, class Sample, class I = int, class J = int,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
int linear_matroid_parity_size(const SparseMatrix<F> &matroid,
const vc<pair<I, J>> &pairs,
Sample &&sample, int trials = 1)
{
assert(trials >= 1);
using namespace internal::linear_matroid_detail;
auto work_pairs = sparse_parity_pairs(matroid.template shape<int>().second, pairs);
SparseParityRank<F> rank(matroid, work_pairs);
vc<unsigned char> active(pairs.size(), 1);
int best = 0;
for (int trial = 0; trial < trials; trial++)
best = max(best, rank(active, sample));
return best;
}
template <class F, class Sample,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
int linear_matroid_parity_size(const SparseMatrix<F> &matroid,
Sample &&sample, int trials = 1)
{
auto pairs = internal::linear_matroid_detail::consecutive_pairs(matroid.template shape<int>().second);
return linear_matroid_parity_size(matroid, pairs, std::forward<Sample>(sample), trials);
}
template <class F, class Sample, class I = int, class J = int,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
vc<int> linear_matroid_parity_restore(const SparseMatrix<F> &matroid,
const vc<pair<I, J>> &pairs,
Sample &&sample, int trials = 1)
;
#line 7827
template <class F, class Sample,
enable_if_t<is_invocable_r_v<typename F::S, Sample &>, int> = 0>
vc<int> linear_matroid_parity_restore(const SparseMatrix<F> &matroid,
Sample &&sample, int trials = 1)
;
template <class F, class I = int, class J = int>
int linear_matroid_parity_size(const SparseMatrix<F> &matroid,
const vc<pair<I, J>> &pairs, int trials = 1)
{
return linear_matroid_parity_size(matroid, pairs, random_modint<typename F::S>, trials);
}
template <class F>
int linear_matroid_parity_size(const SparseMatrix<F> &matroid, int trials = 1)
{
return linear_matroid_parity_size(matroid, random_modint<typename F::S>, trials);
}
template <class F>
int linear_matroid_parity_size(const SparseMatrix<F> &matroid,
initializer_list<pair<int, int>> pairs, int trials = 1)
{
return linear_matroid_parity_size(matroid, vc<pair<int, int>>(pairs), trials);
}
template <class F, class I = int, class J = int>
vc<int> linear_matroid_parity_restore(const SparseMatrix<F> &matroid,
const vc<pair<I, J>> &pairs, int trials = 1)
;
template <class F>
vc<int> linear_matroid_parity_restore(const SparseMatrix<F> &matroid, int trials = 1)
;
template <class F>
vc<int> linear_matroid_parity_restore(const SparseMatrix<F> &matroid,
initializer_list<pair<int, int>> pairs, int trials = 1)
;
#line 7914
template <class Cost = void>
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<void>
{
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 <bool is_directed, class Cost = void, bool is_erasable = false>
struct Graph
{
using E = Edge<Cost>;
protected:
template <class C, bool unweighted = is_void_v<C>>
struct InternalEdge
{
int to, index;
C cost;
};
template <class C>
struct InternalEdge<C, true>
{
int to, index;
static constexpr ll cost = 1;
};
using GE = conditional_t<is_erasable, E, InternalEdge<Cost>>;
using Weight = decay_t<decltype(E::cost)>;
int n = 0, m = 0, era = 0;
CSR<GE, is_erasable> g;
vc<int> eid_to_elist_id;
static E make_edge(int from, int to, const Weight &cost, int index)
{
if constexpr (is_void_v<Cost>)
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<GE>::const_iterator it;
mutable E e;
OutEdgeIter(int from, typename vc<GE>::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 <class I = ll>
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 <class F>
void build(F input_edge)
{
vc<int> 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<GE, is_erasable>(row_sizes);
if constexpr (is_erasable)
eid_to_elist_id.assign((is_directed ? 1 : 2) * m, -1);
vc<int> 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<Cost>)
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<Cost>)
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 <class I>
Graph(int n, const vc<pair<I, I>> &es) : n(n), m(es.size()), era(0)
{
build(LMD(i, (tuple{es[i].first, es[i].second, Weight(1)})));
}
template <class I, class C = Cost, enable_if_t<!is_void_v<C>, int> = 0>
Graph(int n, const vc<pair<I, I>> &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 <class I, class C, enable_if_t<is_same_v<C, Cost> && !is_void_v<C>, int> = 0>
Graph(int n, const vc<tuple<I, I, C>> &es) : n(n), m(es.size()), era(0)
{
build(LMD(i, es[i]));
}
Graph(int n, const vc<E> &es) : n(n), m(es.size()), era(0)
{
build(LMD(i, (tuple{es[i].from, es[i].to, es[i].cost})));
}
template <class I = ll>
I size() const { return n; }
auto out_edges(int v) const
{
return OutEdgeRow(this, v);
}
#line 8189
vc<E> edges() const
;
#line 8267
private:
#line 8293
};
template <bool is_directed, bool is_erasable = false, class I>
Graph(int, const vc<pair<I, I>> &) -> Graph<is_directed, void, is_erasable>;
template <bool is_directed, bool is_erasable = false, class I, class Cost>
Graph(int, const vc<tuple<I, I, Cost>> &) -> Graph<is_directed, Cost, is_erasable>;
template <bool is_directed, bool is_erasable = false, class I, class Cost>
Graph(int, const vc<pair<I, I>> &, const Cost &) -> Graph<is_directed, Cost, is_erasable>;
template <bool is_directed, bool is_erasable = false, class Cost>
Graph(int, const vc<Edge<Cost>> &) -> Graph<is_directed, Cost, is_erasable>;
template <class Cost = void, bool is_erasable = false>
using GraphDirected = Graph<true, Cost, is_erasable>;
template <class Cost = void, bool is_erasable = false>
using GraphUndirected = Graph<false, Cost, is_erasable>;
#line 8327
namespace internal
{
struct BipartiteGraphIndex
{
vc<int> left, right, index;
CSR<int> adjacency;
template <class Cost, bool is_erasable, class Color>
BipartiteGraphIndex(const GraphUndirected<Cost, is_erasable> &graph, const vc<Color> &color)
{
const int n = graph.template size<int>();
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<int> degree(left.size());
for (int u = 0; u < int(left.size()); u++) degree[u] = graph.out_edges(left[u]).size();
adjacency = CSR<int>(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<int> left, right, parent_right;
optional<int> free_right;
CPP_DUMP_DEFINE_DATA(left, right, parent_right, free_right);
};
private:
int right_count = 0, matched = 0;
CSR<int> adjacency_;
vc<int> left_mate_, right_mate_;
vc<int> 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 <class Cost, bool is_erasable, class Color>
BipartiteMatchingState(const GraphUndirected<Cost, is_erasable> &graph, const vc<Color> &color)
: BipartiteMatchingState(internal::BipartiteGraphIndex(graph, color)) {}
BipartiteMatchingState(int right_vertices, CSR<int> adjacency)
: right_count(right_vertices), adjacency_(move(adjacency)),
left_mate_(adjacency_.template size<int>(), -1), right_mate_(right_vertices, -1)
{
assert(right_vertices >= 0);
for (int v : adjacency_.get_elist()) assert(0 <= v && v < right_count);
}
template <class I = int>
BipartiteMatchingState(int right_vertices, const vvc<I> &adjacency)
: BipartiteMatchingState(right_vertices, CSR<int>(adjacency))
{
for (const auto &row : adjacency) for (auto v : row)
assert(u128(v) < unsigned(right_vertices));
}
template <class I = int>
BipartiteMatchingState(int right_vertices, initializer_list<vc<I>> adjacency)
: BipartiteMatchingState(right_vertices, vvc<I>(adjacency)) {}
template <class I, bool erasable>
BipartiteMatchingState(int right_vertices, const CSR<I, erasable> &adjacency)
: BipartiteMatchingState(right_vertices, CSR<int>(adjacency))
{
for (int u = 0; u < adjacency.template size<int>(); u++) for (auto v : adjacency[u])
assert(u128(v) < unsigned(right_vertices));
}
int left_size() const { return adjacency_.template size<int>(); }
int right_size() const { return right_count; }
const CSR<int> &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<int> left_index(int vertex) const
{
if (vertex_index_.empty())
return 0 <= vertex && vertex < left_size() ? optional<int>(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<int>(u) : nullopt;
}
vc<pair<int, int>> matching() const
{
vc<pair<int, int>> 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 <bool CollectRight = true>
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<bool> 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<false>(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 F = FieldAddSubMulDiv<modint998244353>, class Cost, bool is_erasable, class Color,
class Sample = decltype(random_modint<typename F::S>) &, bool Sparse = false>
auto transversal_linear_representation(const GraphUndirected<Cost, is_erasable> &graph,
const vc<Color> &color, Sample &&sample = random_modint<typename F::S>)
{
internal::BipartiteGraphIndex indexed(graph, color);
const int n = indexed.left.size(), dimension = indexed.right.size();
internal::LinearRepresentationBuilder<F, Sparse> columns(dimension, n);
vc<int> 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 F = FieldAddSubMulDiv<modint998244353>, class Sample = decltype(random_modint<typename F::S>) &, class I = int, bool Sparse = false>
auto transversal_linear_representation(int right_vertices, const vvc<I> &adjacency,
Sample &&sample = random_modint<typename F::S>)
{
assert(right_vertices >= 0);
const int n = adjacency.size();
internal::LinearRepresentationBuilder<F, Sparse> columns(right_vertices, n);
vc<int> 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 F = FieldAddSubMulDiv<modint998244353>, class Sample = decltype(random_modint<typename F::S>) &,
class I = int, bool erasable = false, bool Sparse = false>
auto transversal_linear_representation(int right_vertices, const CSR<I, erasable> &adjacency,
Sample &&sample = random_modint<typename F::S>)
{
assert(right_vertices >= 0);
const int n = adjacency.size();
internal::LinearRepresentationBuilder<F, Sparse> columns(right_vertices, n);
vc<int> 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 F = FieldAddSubMulDiv<modint998244353>, class Sample = decltype(random_modint<typename F::S>) &, class I = int, bool Sparse = false>
auto transversal_linear_representation(int right_vertices, initializer_list<vc<I>> adjacency,
Sample &&sample = random_modint<typename F::S>)
{
return transversal_linear_representation<F, Sample, I, Sparse>(right_vertices, vvc<I>(adjacency),
std::forward<Sample>(sample));
}
class TransversalMatroid
{
BipartiteMatchingState matching;
vc<bool> selected;
public:
template <class Cost, bool is_erasable, class Color>
TransversalMatroid(const GraphUndirected<Cost, is_erasable> &graph, const vc<Color> &color)
: matching(graph, color), selected(matching.left_size()) {}
template <class I = int>
TransversalMatroid(int right_vertices, vvc<I> 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<int> element(int vertex) const { return matching.left_index(vertex); }
template <class F = FieldAddSubMulDiv<modint998244353>, class Sample = decltype(random_modint<typename F::S>) &>
SparseMatrix<F> sparse_linear_representation(Sample &&sample = random_modint<typename F::S>) const
{
return transversal_linear_representation<F, Sample, int, false, true>(matching.right_size(), matching.adjacency(),
std::forward<Sample>(sample));
}
template <class I = int>
void build(const vc<I> &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 <auto init, auto main2, auto test>
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<init, main2, test> main_dummy;
int main() {}
// submit-code: hash=66bed88db000 source=66bed88db0003b2cf2e4737ba89702e4b00120ec86341ac99026a3b8dff9105f input=85632aaa77d19fe7e645b511983fff0e9de0d45cd4db5a6e74e30c59c4cae875 body=db0744225f7d8f01468aff543cfea4de04ae7907d2c694b5c926bf6230af403d
miscalc