// 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 // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_all.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_all_but_modint.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_types.hpp /** * @brief テンプレート(型) * @docs docs/template/template_types.md */ // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin core_types // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin float_types #include using namespace std; #if __cplusplus > 202002L && defined(__STDCPP_FLOAT128_T__) #include using f128 = std::float128_t; #elif defined(__SIZEOF_FLOAT128__) using f128 = __float128; #else #error "f128 requires a compiler with IEEE binary128 support, such as GCC on x86_64." #endif #define LIBRARY_HAS_FLOAT128 1 // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end float_types #include using namespace std; #ifndef EPS #define EPS 1e-11 #endif using ld = decltype(EPS); using ll = long long; using uint = unsigned int; using ull = unsigned long long; using pll = pair; using tlll = tuple; using tllll = tuple; #define vc vector template using vvc = vc>; template using vvvc = vc>>; using vb = vc; using vl = vc; using vpll = vc; using vtlll = vc; using vtllll = vc; using vstr = vc; using vvb = vvc; using vvl = vvc; template using pql = priority_queue, greater>; template using pqg = priority_queue; #ifdef __SIZEOF_INT128__ using i128 = __int128_t; using u128 = __uint128_t; #endif #define cauto const auto // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end core_types // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_float128.hpp /** * @brief 四倍精度浮動小数点数 * @docs docs/template/template_types.md */ // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin float_math #if __cplusplus > 202002L && defined(__STDCPP_FLOAT128_T__) && \ (defined(_GLIBCXX_HAVE_FLOAT128_MATH) || defined(_GLIBCXX_LDOUBLE_IS_IEEE_BINARY128)) #define LIBRARY_USE_QUADMATH 0 #else #include #define LIBRARY_USE_QUADMATH 1 //! https://gcc.gnu.org/onlinedocs/libquadmath/Math-Library-Routines.html #define _p_F128_UNARY(name) \ inline f128 name(f128 x) { return f128(name##q(__float128(x))); } _p_F128_UNARY(acos) _p_F128_UNARY(acosh) _p_F128_UNARY(asin) _p_F128_UNARY(asinh) _p_F128_UNARY(atan) _p_F128_UNARY(atanh) _p_F128_UNARY(cbrt) _p_F128_UNARY(ceil) _p_F128_UNARY(cos) _p_F128_UNARY(cosh) _p_F128_UNARY(erf) _p_F128_UNARY(erfc) _p_F128_UNARY(exp) _p_F128_UNARY(exp2) _p_F128_UNARY(expm1) _p_F128_UNARY(fabs) _p_F128_UNARY(floor) _p_F128_UNARY(lgamma) _p_F128_UNARY(log) _p_F128_UNARY(log10) _p_F128_UNARY(log1p) _p_F128_UNARY(log2) _p_F128_UNARY(logb) _p_F128_UNARY(nearbyint) _p_F128_UNARY(rint) _p_F128_UNARY(round) _p_F128_UNARY(sin) _p_F128_UNARY(sinh) _p_F128_UNARY(sqrt) _p_F128_UNARY(tan) _p_F128_UNARY(tanh) _p_F128_UNARY(tgamma) _p_F128_UNARY(trunc) #undef _p_F128_UNARY template , int> = 0> inline f128 abs(T x) { return f128(fabsq(__float128(x))); } #define _p_F128_BINARY(name) \ inline f128 name(f128 x, f128 y) { return f128(name##q(__float128(x), __float128(y))); } \ template , int> = 0> \ inline f128 name(f128 x, T y) { return name(x, f128(y)); } \ template , int> = 0> \ inline f128 name(T x, f128 y) { return name(f128(x), y); } _p_F128_BINARY(atan2) _p_F128_BINARY(copysign) _p_F128_BINARY(fdim) _p_F128_BINARY(fmax) _p_F128_BINARY(fmin) _p_F128_BINARY(fmod) _p_F128_BINARY(hypot) _p_F128_BINARY(nextafter) _p_F128_BINARY(pow) _p_F128_BINARY(remainder) #undef _p_F128_BINARY inline f128 fma(f128 x, f128 y, f128 z) { return f128(fmaq(__float128(x), __float128(y), __float128(z))); } inline f128 hypot(f128 x, f128 y, f128 z) { return hypot(hypot(x, y), z); } namespace template_float128_detail { template constexpr bool arithmetic = is_arithmetic_v || is_same_v; } #define _p_F128_TERNARY_MIXED(name) \ template && template_float128_detail::arithmetic, int> = 0> \ inline f128 name(f128 x, T y, U z) { return name(x, f128(y), f128(z)); } \ template && !is_same_v && template_float128_detail::arithmetic, int> = 0> \ inline f128 name(T x, f128 y, U z) { return name(f128(x), y, f128(z)); } \ template && !is_same_v && template_float128_detail::arithmetic && !is_same_v, int> = 0> \ inline f128 name(T x, U y, f128 z) { return name(f128(x), f128(y), z); } _p_F128_TERNARY_MIXED(fma) _p_F128_TERNARY_MIXED(hypot) #undef _p_F128_TERNARY_MIXED inline f128 frexp(f128 x, int *exponent) { return f128(frexpq(__float128(x), exponent)); } inline f128 ldexp(f128 x, int exponent) { return f128(ldexpq(__float128(x), exponent)); } inline f128 scalbn(f128 x, int exponent) { return f128(scalbnq(__float128(x), exponent)); } inline f128 scalbln(f128 x, long exponent) { return f128(scalblnq(__float128(x), exponent)); } inline f128 modf(f128 x, f128 *integer) { __float128 value; const auto fraction = modfq(__float128(x), &value); *integer = f128(value); return f128(fraction); } inline f128 remquo(f128 x, f128 y, int *quotient) { return f128(remquoq(__float128(x), __float128(y), quotient)); } inline long lrint(f128 x) { return lrintq(__float128(x)); } inline long lround(f128 x) { return lroundq(__float128(x)); } inline long long llrint(f128 x) { return llrintq(__float128(x)); } inline long long llround(f128 x) { return llroundq(__float128(x)); } inline int ilogb(f128 x) { return ilogbq(__float128(x)); } template , int> = 0> inline bool isfinite(T x) { return finiteq(__float128(x)); } template , int> = 0> inline bool isinf(T x) { return isinfq(__float128(x)); } template , int> = 0> inline bool isnan(T x) { return isnanq(__float128(x)); } template , int> = 0> inline bool signbit(T x) { return signbitq(__float128(x)); } template , int> = 0> inline bool isnormal(T x) { return isfinite(x) && abs(x) >= numeric_limits::min(); } template , int> = 0> inline int fpclassify(T x) { if (isnan(x)) return FP_NAN; if (isinf(x)) return FP_INFINITE; if (x == 0) return FP_ZERO; return isnormal(x) ? FP_NORMAL : FP_SUBNORMAL; } #endif inline f128 nexttoward(f128 x, long double y) { return nextafter(x, f128(y)); } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end float_math // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin float_format namespace template_float128_detail { inline bool parse(string_view s, f128 &x) { if (!s.empty() && s.front() == '+') { s.remove_prefix(1); if (s.empty() || s.front() == '-') return false; } #if LIBRARY_USE_QUADMATH string token(s); char *end; errno = 0; const __float128 value = strtoflt128(token.c_str(), &end); if (end == token.data() || end != token.data() + token.size()) return false; if (errno == ERANGE && (value == 0 || isinfq(value))) return false; x = f128(value); return true; #else auto [p, ec] = from_chars(s.data(), s.data() + s.size(), x); return ec == errc{} && p == s.data() + s.size(); #endif } inline string format(f128 x, chars_format style, int precision) { string s(128, '\0'); while (true) { #if LIBRARY_USE_QUADMATH const char *spec = style == chars_format::fixed ? "%.*Qf" : style == chars_format::scientific ? "%.*Qe" : "%.*Qg"; const int n = quadmath_snprintf(s.data(), s.size(), spec, precision, __float128(x)); if (n < 0) abort(); if (size_t(n) < s.size()) { s.resize(size_t(n)); return s; } s.resize(size_t(n) + 1); #else auto [p, ec] = to_chars(s.data(), s.data() + s.size(), x, style, precision); if (ec == errc{}) { s.resize(size_t(p - s.data())); return s; } s.resize(s.size() * 2); #endif } } } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end float_format // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:template/template_float128.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin integer_io #ifdef __SIZEOF_INT128__ 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; } #endif // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end integer_io // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:template/template_types.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_rep.hpp /** * @brief テンプレート(rep) * @docs docs/template/template_rep.md */ #define overload4(_1, _2, _3, _4, name, ...) name #define LIBRARY_REPEAT_LOOP(T, i, l, r, d) \ for (auto [i, library_repeat_end, library_repeat_step] = array{T(l), T(r), T(d)}; \ library_repeat_step > 0 ? i < library_repeat_end : i > library_repeat_end; \ i += library_repeat_step) #define rep1(i, n) LIBRARY_REPEAT_LOOP(ll, i, 0, n, 1) #define rep2(i, l, r) LIBRARY_REPEAT_LOOP(ll, i, l, r, 1) #define rep3(i, l, r, d) LIBRARY_REPEAT_LOOP(ll, i, l, r, d) #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 repi3(i, l, r, d) LIBRARY_REPEAT_LOOP(int, i, l, r, d) #define repi(...) overload4(__VA_ARGS__, repi3, repi2, repi1)(__VA_ARGS__) #define fe(...) for (auto __VA_ARGS__) #define fec(...) for (cauto &__VA_ARGS__) #define fem(...) for (auto &__VA_ARGS__) // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:template/template_rep.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_math.hpp #ifndef INF #define INF 4'000'000'000'000'000'037LL #endif #ifndef EPS #define EPS 1e-11 #endif // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin arithmetic_declarations /** * @brief pair・tuple・array の成分ごとの加算・減算 * @docs docs/template/template_arithmetic.md */ template constexpr pair &operator+=(pair &a, const P &b); template constexpr pair operator+(pair a, const P &b); template constexpr pair &operator-=(pair &a, const P &b); template constexpr pair operator-(pair a, const P &b); template constexpr pair operator-(pair a); template constexpr array &operator+=(array &a, const A &b); template constexpr array operator+(array a, const A &b); template constexpr array &operator-=(array &a, const A &b); template constexpr array operator-(array a, const A &b); template constexpr array operator-(array a); template constexpr tuple &operator+=(tuple &a, const Tp &b); template constexpr tuple operator+(tuple a, const Tp &b); template constexpr tuple &operator-=(tuple &a, const Tp &b); template constexpr tuple operator-(tuple a, const Tp &b); template constexpr tuple operator-(tuple a); // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin arithmetic template constexpr pair &operator+=(pair &a, const P &b) { a.first += b.first; a.second += b.second; return a; } template constexpr pair operator+(pair a, const P &b) { return a += b; } template constexpr pair &operator-=(pair &a, const P &b) { a.first -= b.first; a.second -= b.second; return a; } template constexpr pair operator-(pair a, const P &b) { return a -= b; } template constexpr pair operator-(pair a) { a.first = -a.first; a.second = -a.second; return a; } template constexpr array &operator+=(array &a, const A &b) { for (size_t i = 0; i < n; i++) a[i] += b[i]; return a; } template constexpr array operator+(array a, const A &b) { return a += b; } template constexpr array &operator-=(array &a, const A &b) { for (size_t i = 0; i < n; i++) a[i] -= b[i]; return a; } template constexpr array operator-(array a, const A &b) { return a -= b; } template constexpr array operator-(array a) { for (auto &ai : a) ai = -ai; return a; } namespace internal { template constexpr auto &tuple_add_impl(A &a, const B &b, const index_sequence) { ((get(a) += get(b)), ...); return a; } template constexpr auto &tuple_sub_impl(A &a, const B &b, const index_sequence) { ((get(a) -= get(b)), ...); return a; } template constexpr auto &tuple_neg_impl(A &a, const index_sequence) { ((get(a) = -get(a)), ...); return a; } }; template constexpr tuple &operator+=(tuple &a, const Tp &b) { return internal::tuple_add_impl(a, b, make_index_sequence>>{}); } template constexpr tuple operator+(tuple a, const Tp &b) { return a += b; } template constexpr tuple &operator-=(tuple &a, const Tp &b) { return internal::tuple_sub_impl(a, b, make_index_sequence>>{}); } template constexpr tuple operator-(tuple a, const Tp &b) { return a -= b; } template constexpr tuple operator-(tuple a) { internal::tuple_neg_impl(a, make_index_sequence{}); return a; } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end arithmetic // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end arithmetic_declarations // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:utils/is_integral_ext.hpp /** * @brief $128$ ビット整数を含めた整数判定 * @docs docs/utils/is_integral_ext.md */ template constexpr bool is_integral_ext = is_integral_v || is_same_v || is_same_v; template constexpr bool is_signed_ext = is_signed_v || is_same_v; template constexpr bool is_unsigned_ext = is_unsigned_v || is_same_v; // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:utils/is_integral_ext.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:utils/integer_arithmetic.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:utils/make_unsigned_ext.hpp /** * @brief $128$ ビット整数に対応した make_singed と make_unsigned * @docs docs/utils/make_unsigned_ext.md */ template struct make_unsigned_ext { using type = make_unsigned_t; }; template <> struct make_unsigned_ext { using type = u128; }; template <> struct make_unsigned_ext { using type = u128; }; template using make_unsigned_ext_t = typename make_unsigned_ext::type; template struct make_signed_ext { using type = make_signed_t; }; template <> struct make_signed_ext { using type = i128; }; template using make_signed_ext_t = typename make_signed_ext::type; // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:utils/make_unsigned_ext.hpp /** * @brief 整数の符号・絶対値・剰余を保つ型変換 * @docs docs/utils/integer_arithmetic.md */ template constexpr bool is_negative(T x) { static_assert(is_integral_ext); if constexpr (is_signed_ext) return x < 0; return false; } template constexpr make_unsigned_ext_t unsigned_abs(T x) { static_assert(is_integral_ext && !is_same_v); using U = make_unsigned_ext_t; return is_negative(x) ? U(U(0) - U(x)) : U(x); } template > struct unsigned_arithmetic { using type = T; }; template struct unsigned_arithmetic { static_assert(!is_same_v); using type = common_type_t>; }; template using unsigned_arithmetic_t = typename unsigned_arithmetic::type; // mod 2^w (w は R の幅) で合同な値を返す。 template constexpr R wrapping_cast(T x) { static_assert(is_integral_ext && !is_same_v); static_assert(is_integral_ext && !is_same_v); if constexpr (is_signed_ext) { using U = make_unsigned_ext_t; const U bits = U(x); if (bits <= U(numeric_limits::max())) return R(bits); return R(-1) - R(U(~bits)); } else return R(x); } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:utils/integer_arithmetic.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:utils/default_infty.hpp #ifndef INF #define INF 4'000'000'000'000'000'037LL #endif /** * @brief 型ごとの既定の無限大 * @docs docs/utils/default_infty.md */ template constexpr decltype(auto) default_infty(); namespace default_infty_detail { template struct is_product : false_type {}; template struct is_product> : true_type {}; template struct is_product> : true_type {}; template struct is_product> : true_type {}; template constexpr T product_value(index_sequence) { return T{default_infty>()...}; } template struct has_infty : false_type {}; template struct has_infty> : true_type {}; template const T &custom_value() { static const T value = T::infty(); return value; } template inline constexpr bool unsupported = false; } template constexpr decltype(auto) default_infty() { if constexpr (default_infty_detail::has_infty::value) return default_infty_detail::custom_value(); else if constexpr (default_infty_detail::is_product>::value) return default_infty_detail::product_value>( make_index_sequence>>{}); else if constexpr (is_same_v || is_same_v) return T(INF) * T(INF); else if constexpr (is_integral_ext && !is_same_v) { if constexpr (sizeof(T) >= sizeof(ll)) return T(INF); else if constexpr (numeric_limits::digits >= 31) return (T(1) << 30) - 1; else return T(numeric_limits::max() / 2); } else if constexpr (numeric_limits::has_infinity) return numeric_limits::infinity(); else static_assert(default_infty_detail::unsupported, "No default infinity for this type; specify infty explicitly or define T::infty()."); } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:utils/default_infty.hpp /** * @brief テンプレート(演算) * @docs docs/template/template_math.md */ // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin math template inline bool chmin(T &a, U b) { return a > b ? a = b, true : false; } template inline bool chmax(T &a, U b) { return a < b ? a = b, true : false; } template || is_same_v, int> = 0> inline constexpr T abs(T x) { return is_negative(x) ? -x : x; } namespace template_math_detail { template constexpr common_type_t gcd(T a, U b) { using R = common_type_t; using W = make_unsigned_ext_t; W x = W(unsigned_abs(a)), y = W(unsigned_abs(b)); while (y != 0) { W r = x % y; x = y, y = r; } return R(x); } template constexpr common_type_t lcm(T a, U b) { using R = common_type_t; using W = make_unsigned_ext_t; W x = W(unsigned_abs(a)), y = W(unsigned_abs(b)); return x == 0 || y == 0 ? R(0) : R(x / template_math_detail::gcd(x, y) * y); } } template && !is_same_v, int> = 0> constexpr common_type_t gcd(i128 a, T b) { return template_math_detail::gcd(a, b); } template && !is_same_v && !is_same_v && !is_same_v, int> = 0> constexpr common_type_t gcd(T a, i128 b) { return template_math_detail::gcd(a, b); } template && !is_same_v, int> = 0> constexpr common_type_t gcd(u128 a, T b) { return template_math_detail::gcd(a, b); } template && !is_same_v && !is_same_v && !is_same_v, int> = 0> constexpr common_type_t gcd(T a, u128 b) { return template_math_detail::gcd(a, b); } template && !is_same_v, int> = 0> constexpr common_type_t lcm(i128 a, T b) { return template_math_detail::lcm(a, b); } template && !is_same_v && !is_same_v && !is_same_v, int> = 0> constexpr common_type_t lcm(T a, i128 b) { return template_math_detail::lcm(a, b); } template && !is_same_v, int> = 0> constexpr common_type_t lcm(u128 a, T b) { return template_math_detail::lcm(a, b); } template && !is_same_v && !is_same_v && !is_same_v, int> = 0> constexpr common_type_t lcm(T a, u128 b) { return template_math_detail::lcm(a, b); } template && is_integral_ext>> inline constexpr T divfloor(U a, V b) { return T(a) / T(b) - (T(a) % T(b) && (T(a) ^ T(b)) < 0); } template && is_integral_ext>> inline constexpr T divceil(U a, V b) { return T(a) / T(b) + (T(a) % T(b) && (T(a) ^ T(b)) >= 0); } template && is_integral_ext>> inline constexpr T safemod(U a, V b) { const T x = T(a), y = T(b); if constexpr (is_signed_ext) if (y == T(-1)) return T(0); const T r = x % y; return r != T(0) && is_negative(x) != is_negative(y) ? T(r + y) : r; } template constexpr T ipow(U a, V b) { assert(b >= 0); if (b == 0) return 1; if (a == 0 || a == 1) return a; if (a < 0 && a == -1) return b & 1 ? -1 : 1; T res = 1, tmp = a; while (true) { if (b & 1) res *= tmp; b >>= 1; if (b == 0) break; tmp *= tmp; } return res; } template T mul_limited(A a, B b, M m) { assert(a >= 0 && b >= 0 && m >= 0); if (b == 0) return 0; return T(a) > T(m) / T(b) ? T(m) : T(a) * T(b); } template T mul_limited(A a, B b) { return mul_limited(a, b, default_infty()); } template T pow_limited(A a, B b, M m) { assert(a >= 0 && b >= 0 && m >= 0); if (a <= 1 || b == 0) return min(ipow(a, b), T(m)); T res = 1, tmp = a; while (true) { if (b & 1) { if (res > T(m) / tmp) return m; res *= tmp; } b >>= 1; if (b == 0) break; if (tmp > T(m) / tmp) return m; tmp *= tmp; } return res; } template T pow_limited(A a, B b) { return pow_limited(a, b, default_infty()); } template constexpr T iroot(A a, K k) { assert(a >= 0 && k >= 1); if (a <= 1 || k == 1) return a; if (k == 2) { const T aa = T(a); T x = T(sqrtl((long double)a)); while (x > aa / x) x--; while (x < numeric_limits::max()) { const T y = x + 1; if (y > aa / y) break; x = y; } return x; } auto isok = [&](T x) -> bool { if (x == 0) return true; T res = 1, k2 = k; while (true) { if (k2 & 1) { if (res > T(a) / x) return false; res *= x; } k2 >>= 1; if (k2 == 0) break; if (x > T(a) / x) return false; x *= x; } return res <= T(a); }; T x = pow(a, 1.0 / k); bool up = true; while (!isok(x)) up = false, x--; if (up) { while (x < numeric_limits::max() && isok(x + 1)) x++; } return x; } template constexpr T iroot_ceil(A a, K k) { T x = iroot(a, k); return ipow(x, k) == a ? x : x + 1; } //! https://misawa.github.io/others/avoid_errors/techniques_to_avoid_errors.html template int SGN(A a, D eps = EPS) { return int(a > eps) - int(a < -eps); } // 位取り記数法と同じ順番(下位桁が後ろ) // 0 に対しては {0} が返る template vc base_repr(U val, V base) { assert(val >= 0); assert(base >= 2); if (val == 0) return {0}; vc a; while (val > 0) { a.emplace_back(val % base); val /= base; } reverse(a.begin(), a.end()); return a; } // 位取り記数法と同じ順番(下位桁が後ろ) template vc base_repr(U val, V base, int n) { assert(val >= 0); assert(base >= 2); assert(n >= 0); vc a(n); repi(i, n) { a[i] = val % base; val /= base; } reverse(a.begin(), a.end()); return a; } template string base_repr_str(U val, int base) { assert(val >= 0); assert(2 <= base && base <= 36); auto a = base_repr(val, base); string s = ""; for (cauto &ai : a) s += (ai < 10 ? '0' + ai : (use_upper ? 'A' : 'a') + (ai - 10)); return s; } template string base_repr_str(U val, int base, int n) { assert(val >= 0); assert(2 <= base && base <= 36); assert(n >= 0); auto a = base_repr(val, base, n); string s = ""; for (cauto &ai : a) s += (ai < 10 ? '0' + ai : (use_upper ? 'A' : 'a') + (ai - 10)); return s; } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end math // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:template/template_math.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_vector.hpp /** * @brief テンプレート(vector) * @docs docs/template/template_vector.md */ #define ALL(a) (a).begin(), (a).end() template inline T SZ(const V &x) { return x.size(); } #define eb emplace_back #define LMD(x, fx) ([&](const auto &x) { return fx; }) template auto gen_vec(int n, const F &f) { assert(n >= 0); vc res; res.reserve(n); repi(i, n) res.eb(f(i)); return res; } #define GEN_VEC(n, i, fi) (gen_vec(n, LMD(i, fi))) namespace template_vector_detail { template struct nested_vector { using type = vc::type>; }; template struct nested_vector { using type = T; }; template void populate_dimensions(typename nested_vector::type &result, const V *sizes, const T &init) { if constexpr (depth == 1) { typename nested_vector::type replacement(size_t(*sizes), init); result.swap(replacement); } else { result.resize(size_t(*sizes)); for (auto &child : result) populate_dimensions(child, sizes + 1, init); } } template typename nested_vector::type build_dimensions(const V *sizes, const T &init) { if constexpr (depth == 0) return init; else { typename nested_vector::type result; populate_dimensions(result, sizes, init); return result; } } } template auto dvec(const V (&sz)[d], const T &init) { if constexpr (i >= d) return init; else return template_vector_detail::build_dimensions(sz + i, init); } template auto dvec(const ll (&sz)[d], const T &init) { return dvec(sz, init); } template void fill(V &v, const T &value) { if constexpr (is_assignable_v) std::fill(std::begin(v), std::end(v), value); else for (auto &row : v) fill(row, value); } template optional ctol(const char &c, const string &s) { repi(i, SZ(s)) if (s[i] == c) return T(i); return nullopt; } template vc stov(const string &s, char first) { return gen_vec(SZ(s), [&](int i) -> T { return s[i] - first; }); } template optional> stov(const string &s, const string &t) { vc res; res.reserve(s.size()); for (char c : s) { auto index = ctol(c, t); if (!index) return nullopt; res.push_back(*index); } return res; } template string vtos(const vc &v, char first) { string res = ""; fe(vi : v) res += vi + first; return res; } template string vtos(const vc &v, const string &t) { string res = ""; fe(vi : v) res += t[vi]; return res; } template vc concat(const vvc &vs) { vc res; for (cauto &v : vs) res.insert(res.end(), ALL(v)); return res; } template vc concat(const vc &v) { return v; } template vc concat(vc v, const vc &...vs) { (v.insert(v.end(), ALL(vs)), ...); return v; } template vc merged(const vc &a, const vc &b) { vc res; merge(ALL(a), ALL(b), back_inserter(res)); return res; } template T vecget(const vc &v, I i, const T &dflt_negative = -default_infty(), const T &dflt_positive = default_infty()) { if (i < 0) return dflt_negative; if (i >= SZ(v)) return dflt_positive; return v[i]; } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:template/template_vector.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_algo.hpp #ifndef INF #define INF 4'000'000'000'000'000'037LL #endif // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:utils/resolved_infty.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:utils/resolved_value.hpp /** * @brief 値または関数から値を取得 * @docs docs/utils/resolved_value.md */ template , int> = 0> constexpr T resolved_value() { return T(x); } template , long> = 0> const T &resolved_value() { static const T value = T(x()); return value; } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:utils/resolved_value.hpp /** * @brief 既定値・値・関数から無限大を取得 * @docs docs/utils/resolved_infty.md */ template constexpr decltype(auto) resolved_infty() { if constexpr (is_same_v) return default_infty(); else return resolved_value(); } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:utils/resolved_infty.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin monoid_power /** * @brief モノイド・群のべき乗 * @docs docs/algebra/monoid_power.md */ namespace internal { template struct HasMonoidPow : false_type {}; template struct HasMonoidPow(), declval()))>> : true_type {}; } namespace internal_monoid_power { template constexpr void check_exponent(I k) { static_assert(is_integral_ext); if constexpr (is_signed_ext) assert(k >= 0); } template constexpr typename M::S binary_inplace(typename M::S &x, I k) { typename M::S res = M::e(); if (k & 1) res = M::op(res, x); for (k >>= 1; k; k >>= 1) { x = M::op(x, x); if (k & 1) res = M::op(res, x); } return res; } template constexpr typename M::S binary(typename M::S x, I k) { check_exponent(k); return binary_inplace(x, k); } } // 非負の k に対して x を k 回結合する。M::pow が呼び出せればそれを使う。 template constexpr typename M::S pow_monoid(typename M::S x, I k) { if constexpr (is_signed_ext) assert(k >= 0); if constexpr (internal::HasMonoidPow::value) return M::pow(x, k); else return internal_monoid_power::binary_inplace(x, k); } // x の k 乗を返す。負の k には逆元を使う。 template constexpr typename G::S pow_group(typename G::S x, I k) { if constexpr (is_signed_ext) if (k < 0) { x = G::inv(x); return G::op(pow_monoid(x, -(k + 1)), x); } return pow_monoid(x, k); } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end monoid_power /** * @brief テンプレート(アルゴリズム) * @docs docs/template/template_algo.md */ template auto SUM(const V &v) { typename V::value_type s{}; fec(vi : v) s += vi; return s; } template T SUM(const V &v) { T s{}; fec(vi : v) s += vi; return s; } template auto MAX(const V &v) { return *max_element(ALL(v)); } template auto MIN(const V &v) { return *min_element(ALL(v)); } template optional ARGMAX(const V &v) { if (v.empty()) return nullopt; return I(max_element(ALL(v)) - v.begin()); } template optional ARGMIN(const V &v) { if (v.empty()) return nullopt; return I(min_element(ALL(v)) - v.begin()); } template T mex(const V &a) { int n = a.size(); vector exists(n, false); repi(i, n) if (0 <= a[i] && a[i] < n) exists[a[i]] = true; repi(x, n) if (!exists[x]) return x; return n; } // (0, 1. ..., n-1) の順列か判定 template bool is_permutation(const vc &p) { const int n = p.size(); vc b(n, false); repi(i, n) { if (!(0 <= p[i] && p[i] < n)) return false; b[p[i]] = true; } return all_of(ALL(b), [](bool bi) { return bi; }); } template vc permid(const int &n, const int &base_index = 0) { vc p(n); repi(i, n) p[i] = i + base_index; return p; } template vc perminv(const vc &p) { if (p.empty()) return {}; const int n = p.size(); vc q(MAX(p) + 1); repi(i, n) if (p[i] >= 0) q[p[i]] = i; return q; } // a[p[i]] for all i template vc permuted(const vc &a, const vc &p) { const int n = p.size(); vc res(n); repi(i, n) { assert(0 <= p[i] && p[i] < U(a.size())); res[i] = a[p[i]]; } return res; } // p[q[r[i]]] for all i など template vc permuted(const vc &p, const vc &q, const vc &...rs) { return permuted(permuted(p, q), rs...); } template V reversed(const V &v) { return V(v.rbegin(), v.rend()); } #if __cplusplus < 202002L template V sorted(V v, Args&&... args) { sort(ALL(v), forward(args)...); return v; } #else template V sorted(V v, Args&&... args) { ranges::sort(v, forward(args)...); return v; } #endif template > void unique(V &v, Equal equal = {}) { v.erase(std::unique(ALL(v), equal), v.end()); } template > V uniqued(V v, Equal equal = {}) { unique(v, equal); return v; } template , class Equal = equal_to<>> void sortunique(V &v, Compare comp = {}, Equal equal = {}) { sort(ALL(v), comp); unique(v, equal); } template , class Equal = equal_to<>> V sortuniqued(V v, Compare comp = {}, Equal equal = {}) { sortunique(v, comp, equal); return v; } // 01234 -> 12340 template void rotate(V &v, U k) { const U n = v.size(); if (n == 0) return; k = (k % n + n) % n; std::rotate(v.begin(), v.begin() + k, v.end()); } // 01234 -> 12340 template V rotated(V v, U k) { rotate(v, k); return v; } template vvc top(const vvc &a) { if (a.empty()) return {}; const int n = a.size(), m = a[0].size(); vvc b(m, vc(n)); repi(i, n) { assert(SZ(a[i]) == m); repi(j, m) b[j][i] = a[i][j]; } return b; } vstr top(const vstr &a) { vvc a_(a.size()); repi(i, SZ(a)) a_[i] = {ALL(a[i])}; vvc b_ = top(a_); vstr b(b_.size()); repi(i, SZ(b)) b[i] = {ALL(b_[i])}; return b; } template struct has_e0 : false_type {}; template struct has_e0> : true_type {}; template inline constexpr bool has_e0_v = has_e0::value; template struct MonoidAdd { using S = T; static constexpr S op(S a, S b) { return a + b; } static constexpr S e() { if constexpr (has_e0_v) return S::e0(); else return {}; } template () * declval())> static constexpr S pow(const S &a, I k) { return a * k; } }; template struct MonoidMin { using S = T; static constexpr S op(S a, S b) { return min(a, b); } static constexpr decltype(auto) e() { return resolved_infty(); } template static constexpr S pow(const S &a, I k) { return k == 0 ? e() : a; } }; template struct MonoidMax { using S = T; static constexpr S op(S a, S b) { return max(a, b); } static constexpr S e() { return -resolved_infty(); } template static constexpr S pow(const S &a, I k) { return k == 0 ? e() : a; } }; // left_index が 0 なら、長さ n+1 で a.front() が e() // left_index が 1 なら、長さ n で e() がない template vc cuml(const vc &v, int left_index = 0) { const int n = v.size(); vc res(n + 1); res[0] = M::e(); repi(i, n) res[i + 1] = M::op(res[i], v[i]); res.erase(res.begin(), res.begin() + left_index); return res; } // right_index が 0 なら、長さ n+1 で a.back() が e() // right_index が 1 なら、長さ n で e() がない template vc cumr(const vc &v, int right_index = 0) { return reversed(cuml(reversed(v), right_index)); } template vc cumlsum(const vc &v, int left_index = 0) { return cuml>(v, left_index); } template vc cumrsum(const vc &v, int right_index = 0) { return cumr>(v, right_index); } template vc cumlmin(const vc &v, int left_index = 0) { return cuml>(v, left_index); } template vc cumrmin(const vc &v, int right_index = 0) { return cumr>(v, right_index); } template vc cumlmax(const vc &v, int left_index = 0) { return cuml>(v, left_index); } template vc cumrmax(const vc &v, int right_index = 0) { return cumr>(v, right_index); } // デフォルトでは長さ n+1 // left_index, right_index をそれぞれ 1 にすると、左右が削除される template vc adjd(const vc &v, int left_index = 0, int right_index = 0) { int n = v.size(); assert(0 <= left_index && 0 <= right_index && left_index + right_index <= n + 1); vc res(n + 1); if (n == 0) { res[0] = T{}; res.erase(res.end() - right_index, res.end()); res.erase(res.begin(), res.begin() + left_index); return res; } res[0] = v[0]; repi(i, 1, n) res[i] = v[i] - v[i - 1]; res[n] = -v[n - 1]; res.erase(res.end() - right_index, res.end()); res.erase(res.begin(), res.begin() + left_index); return res; } constexpr array DRULgrid = {{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}}; constexpr array DRULplane = {{{0, -1}, {1, 0}, {0, 1}, {-1, 0}}}; // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:template/template_algo.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_binsearch.hpp /** * @brief テンプレート(二分探索) * @docs docs/template/template_binsearch.md */ template struct is_random_access_iterator { static constexpr bool value = is_same_v< typename iterator_traits::iterator_category, random_access_iterator_tag >; }; template constexpr bool is_random_access_iterator_v = is_random_access_iterator::value; // --- LB, UB --- #if __cplusplus < 202002L struct identity { template constexpr T &&operator()(T &&t) const noexcept { return forward(t); } }; namespace internal { template inline T bound_helper(const V &v, Judge judge) { int l = -1, r = v.size(); while (r - l > 1) { int m = (l + r) / 2; if (judge(m)) l = m; else r = m; } return r; } }; // val <= v[i] となる最小の i (val 未満の値の個数) template , class Proj = identity> inline T LB(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) { return internal::bound_helper(v, [&](int i) -> bool { return comp(proj(*(v.begin() + i)), val); }); } // val < v[i] となる最小の i (val 以下の値の個数) template , class Proj = identity> inline T UB(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) { return internal::bound_helper(v, [&](int i) -> bool { return !comp(val, proj(*(v.begin() + i))); }); } #define DEFAULT_COMP less<> #else // val <= v[i] となる最小の i (val 未満の値の個数) template inline T LB(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) { return ranges::lower_bound(v, val, comp, proj) - v.begin(); } // val < v[i] となる最小の i (val 以下の値の個数) template inline T UB(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) { return ranges::upper_bound(v, val, comp, proj) - v.begin(); } #define DEFAULT_COMP ranges::less #endif // --- vector 等の lt, leq, gt, geq --- // v[i] < val となる最大の i (左番兵 -1) template inline auto lt_max(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { static_assert(numeric_limits::is_signed, "index type must represent -1"); return LB(v, val, comp, proj) - 1; } // v[i] <= val となる最大の i (左番兵 -1) template inline auto leq_max(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { static_assert(numeric_limits::is_signed, "index type must represent -1"); return UB(v, val, comp, proj) - 1; } // val < v[i] となる最小の i (右番兵 v.size()) template inline auto gt_min(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { return UB(v, val, comp, proj); } // val <= v[i] となる最小の i (右番兵 v.size()) template inline auto geq_min(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { return LB(v, val, comp, proj); } // v[i] < val となる i の個数 template inline auto lt_cnt(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { return LB(v, val, comp, proj); } // v[i] <= val となる i の個数 template inline auto leq_cnt(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { return UB(v, val, comp, proj); } // val < v[i] となる i の個数 template inline auto gt_cnt(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { return SZ(v) - UB(v, val, comp, proj); } // val <= v[i] となる i の個数 template inline auto geq_cnt(const V &v, const Value &val, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { return SZ(v) - LB(v, val, comp, proj); } // l <= v[i] < r となる i の個数 template inline auto in_cnt(const V &v, L l, R r, Comp comp = {}, Proj proj = {}) -> enable_if_t, T> { if (l > r) return 0; return lt_cnt(v, r, comp, proj) - lt_cnt(v, l, comp, proj); } // --- set 等の lt, leq, gt, geq --- // *it < val となる最大の it (なければ nullopt) template inline auto lt_max(const V &v, const Value &val) -> enable_if_t, optional> { auto it = v.lower_bound(val); if (it == v.begin()) return nullopt; return prev(it); } // *it <= val となる最大の it (なければ nullopt) template inline auto leq_max(const V &v, const Value &val) -> enable_if_t, optional> { auto it = v.upper_bound(val); if (it == v.begin()) return nullopt; return prev(it); } // val < *it となる最小の it (なければ nullopt) template inline auto gt_min(const V &v, const Value &val) -> enable_if_t, optional> { auto it = v.upper_bound(val); if (it == v.end()) return nullopt; return it; } // val <= *it となる最小の it (なければ nullopt) template inline auto geq_min(const V &v, const Value &val) -> enable_if_t, optional> { auto it = v.lower_bound(val); if (it == v.end()) return nullopt; return it; } // --- 自作二分探索 --- namespace internal { template bool binsearch_adjacent(T a, T b) { if (a < b) return a + 1 == b; if (b < a) return b + 1 == a; return false; } }; // (ok, ng) template pair binsearch(const Judge &judge, InitOk init_ok, InitNg init_ng, bool check_ok = true, bool check_ng = true) { T ok(init_ok), ng(init_ng); if (check_ok) assert(judge(ok)); if (check_ng) assert(!judge(ng)); while (!internal::binsearch_adjacent(ok, ng)) { T mid = (ok & ng) + ((ok ^ ng) >> 1); (judge(mid) ? ok : ng) = mid; } return {ok, ng}; } template T binsearch_real(const Judge &judge, InitOk init_ok, InitNg init_ng, int iteration_count = 100, bool check_ok = true, bool check_ng = true) { T ok(init_ok), ng(init_ng); if (check_ok) assert(judge(ok)); if (check_ng) assert(!judge(ng)); repi(_, iteration_count) { T mid = (ok + ng) / 2; (judge(mid) ? ok : ng) = mid; } return ok; } // (ok, ng) template pair expsearch(const Judge &judge, InitVal init_val, bool positive = true) { T cur(init_val), step = 1; const bool cur_ok = judge(cur); auto advance = [&](T x, T d, bool pos) -> T { if (pos) return x > numeric_limits::max() - d ? numeric_limits::max() : x + d; else return x < numeric_limits::lowest() + d ? numeric_limits::lowest() : x - d; }; T prv = advance(cur, 1, !positive); if (prv != cur && judge(prv) != cur_ok) { if (cur_ok) return {cur, prv}; else return {prv, cur}; } while (true) { T nxt = advance(cur, step, positive); assert(nxt != cur && "the boundary must exist in the searched direction"); if (nxt == cur || judge(nxt) != cur_ok) { T ok = cur_ok ? cur : nxt; T ng = cur_ok ? nxt : cur; return binsearch(judge, ok, ng, false, false); } cur = nxt; if (step > numeric_limits::max() / 2) step = numeric_limits::max(); else step *= 2; } } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:template/template_binsearch.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin source:template/template_bit.hpp /** * @brief テンプレート(ビット演算) * @docs docs/template/template_bit.md */ template inline constexpr ull pow2(T k) { return 1ULL << k; } template inline constexpr ull MASK(T k) { return (1ULL << k) - 1ULL; } #if __cplusplus < 202002L // x == 0 ならば 0、そうでなければ 1 + floor(log2(x)) // 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, ... inline constexpr ull bit_width(ull x) { return x == 0 ? 0 : 64 - __builtin_clzll(x); } // 0, 1, 2, 2, 4, 4, 4, 4, 8, 8, ... inline constexpr ull bit_floor(ull x) { return x == 0 ? 0ULL : 1ULL << (bit_width(x) - 1); } // 1, 1, 2, 4, 4, 8, 8, 8, 8, 16, ... inline constexpr ull bit_ceil(ull x) { return x == 0 ? 1ULL : 1ULL << bit_width(x - 1); } inline constexpr ull countr_zero(ull x) { assert(x != 0); return __builtin_ctzll(x); } inline constexpr ull popcount(ull x) { return __builtin_popcountll(x); } inline constexpr bool has_single_bit(ull x) { return popcount(x) == 1; } #else // 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, ... inline constexpr ll bit_width(ll x) { return std::bit_width((ull)x); } // 0, 1, 2, 2, 4, 4, 4, 4, 8, 8, ... inline constexpr ll bit_floor(ll x) { return std::bit_floor((ull)x); } // 1, 1, 2, 4, 4, 8, 8, 8, 8, 16, ... inline constexpr ll bit_ceil(ll x) { return std::bit_ceil((ull)x); } inline constexpr ll countr_zero(ll x) { assert(x != 0); return std::countr_zero((ull)x); } inline constexpr ll popcount(ll x) { return std::popcount((ull)x); } inline constexpr bool has_single_bit(ll x) { return std::has_single_bit((ull)x); } #endif inline constexpr ull lsb_pos(ull x) { assert(x != 0); return countr_zero(x); } inline constexpr ull msb_pos(ull x) { assert(x != 0); return bit_width(x) - 1; } inline constexpr ull lsb_mask(ull x) { assert(x != 0); return x & -x; } inline constexpr ull msb_mask(ull x) { assert(x != 0); return bit_floor(x); } inline constexpr bool btest(ull x, uint k) { return (x >> k) & 1; } template inline void bset(T &x, uint k, bool b = 1) { b ? x |= (1ULL << k) : x &= ~(1ULL << k); } template inline void bflip(T &x, uint k) { x ^= (1ULL << k); } inline constexpr bool bsubset(ull x, ull y) { return (x & y) == x; } inline constexpr bool bsupset(ull x, ull y) { return (x & y) == y; } inline constexpr ull bsetminus(ull x, ull y) { return x & ~y; } // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 end source:template/template_bit.hpp // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin float_io // submit-code-feature: ae4c6fdecee9eecda3393e43aa0d7355 begin float_dump #ifdef LOCAL namespace cpp_dump::_detail { struct export_command; #if LIBRARY_HAS_FLOAT128 inline string export_var(const f128 &, const string &, size_t, size_t, bool, const export_command &); #endif inline string export_var(const u128 &, const string &, size_t, size_t, bool, const export_command &); } #endif #ifdef LOCAL #include