proconlib

This documentation is automatically generated by competitive-verifier/competitive-verifier

View the Project on GitHub anqooqie/proconlib

:heavy_check_mark: tests/matrix/ring.test.cpp

Depends on

Code

// competitive-verifier: STANDALONE
// Source: https://atcoder.jp/contests/abc009/tasks/abc009_4

#include <cstdint>
#include <iostream>
#include <vector>
#include "tools/assert_that.hpp"
#include "tools/matrix.hpp"
#include "tools/monoids.hpp"
#include "tools/pow.hpp"
#include "tools/rings.hpp"
#include "tools/vector.hpp"

using u32 = std::uint32_t;

struct monoid {
  static inline int N;
  using T = tools::matrix<tools::rings::xor_and<u32>>;
  static T op(const T& a, const T& b) {
    return a * b;
  }
  static T e() {
    return T::e(N);
  }
};

u32 solve(const int K, const int M, const std::vector<u32>& A, const std::vector<u32>& C) {
  monoid::N = K;
  tools::matrix<tools::rings::xor_and<u32>> matrix(K, K);
  for (int i = 0; i + 1 < K; ++i) {
    matrix[i][i + 1] = tools::monoids::bit_and<u32>::e();
  }
  for (int j = 0; j < K; ++j) {
    matrix[K - 1][j] = C[K - 1 - j];
  }
  tools::vector<u32> vector(K);
  for (int i = 0; i < K; ++i) {
    vector[i] = A[i];
  }
  return (tools::pow<monoid>(matrix, M - 1) * vector)[0];
}

void sample_01() {
  const int K = 3;
  const int M = 5;
  const std::vector<u32> A = {10, 20, 30};
  const std::vector<u32> C = {7, 19, 13};
  assert_that(solve(K, M, A, C) == 16);
}

void sample_02() {
  const int K = 5;
  const int M = 100;
  const std::vector<u32> A = {2345678901, 1001001001, 3333333333, 3141592653, 1234567890};
  const std::vector<u32> C = {2147483648, 2147483647, 4294967295, 4294967294, 3434343434};
  assert_that(solve(K, M, A, C) == 1067078691);
}

void sample_03() {
  const int K = 30;
  const int M = 999999999;
  const std::vector<u32> A = {11627, 5078, 8394, 6412, 10346, 3086, 3933, 668, 9879, 11739, 4501, 6108, 12336, 8771, 2768, 2438, 2153, 7047, 5476, 313, 1264, 369, 12070, 10743, 10663, 747, 370, 4671, 5235, 3439};
  const std::vector<u32> C = {114, 3613, 3271, 5032, 11241, 6961, 3628, 150, 12191, 2396, 7638, 3046, 11594, 8162, 11136, 786, 9878, 2356, 11660, 1070, 3649, 10882, 9746, 1415, 3307, 7077, 9319, 9981, 3437, 544};
  assert_that(solve(K, M, A, C) == 2148);
}

int main() {
  std::cin.tie(nullptr);
  std::ios_base::sync_with_stdio(false);

  sample_01();
  sample_02();
  sample_03();

  return 0;
}
#line 1 "tests/matrix/ring.test.cpp"
// competitive-verifier: STANDALONE
// Source: https://atcoder.jp/contests/abc009/tasks/abc009_4

#include <cstdint>
#include <iostream>
#include <vector>
#line 1 "tools/assert_that.hpp"



#line 5 "tools/assert_that.hpp"
#include <cstdlib>

#define assert_that_impl(cond, file, line, func) do {\
  if (!cond) {\
    std::cerr << file << ':' << line << ": " << func << ": Assertion `" << #cond << "' failed." << '\n';\
    std::exit(EXIT_FAILURE);\
  }\
} while (false)
#define assert_that(...) assert_that_impl((__VA_ARGS__), __FILE__, __LINE__, __func__)


#line 1 "tools/matrix.hpp"



#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <initializer_list>
#line 10 "tools/matrix.hpp"
#include <iterator>
#include <limits>
#include <optional>
#include <string>
#include <utility>
#line 1 "tools/field.hpp"



#line 1 "tools/commutative_group.hpp"



#line 1 "tools/commutative_monoid.hpp"



#line 1 "tools/monoid.hpp"



#include <concepts>

namespace tools {
  template <typename M>
  concept monoid = requires(typename M::T x, typename M::T y) {
    { M::op(x, y) } -> std::same_as<typename M::T>;
    { M::e() } -> std::same_as<typename M::T>;
  };
}


#line 5 "tools/commutative_monoid.hpp"

namespace tools {
  template <typename M>
  concept commutative_monoid = tools::monoid<M>;
}


#line 1 "tools/group.hpp"



#line 6 "tools/group.hpp"

namespace tools {
  template <typename G>
  concept group = tools::monoid<G> && requires(typename G::T x) {
    { G::inv(x) } -> std::same_as<typename G::T>;
  };
}


#line 6 "tools/commutative_group.hpp"

namespace tools {
  template <typename G>
  concept commutative_group = tools::group<G> && tools::commutative_monoid<G>;
}


#line 1 "tools/commutative_ring.hpp"



#line 1 "tools/ring.hpp"



#line 1 "tools/semiring.hpp"



#line 6 "tools/semiring.hpp"

namespace tools {
  template <typename R>
  concept semiring = tools::commutative_monoid<typename R::add> && tools::monoid<typename R::mul> && std::same_as<typename R::add::T, typename R::mul::T>;
}


#line 6 "tools/ring.hpp"

namespace tools {
  template <typename R>
  concept ring = tools::semiring<R> && tools::commutative_group<typename R::add>;
}


#line 6 "tools/commutative_ring.hpp"

namespace tools {
  template <typename R>
  concept commutative_ring = tools::ring<R> && tools::commutative_monoid<typename R::mul>;
}


#line 6 "tools/field.hpp"

namespace tools {
  template <typename F>
  concept field = tools::commutative_ring<F> && tools::commutative_group<typename F::mul>;
}


#line 1 "tools/groups.hpp"



#line 5 "tools/groups.hpp"
#include <type_traits>
#line 1 "tools/arithmetic.hpp"



#line 1 "tools/integral.hpp"



#line 1 "tools/is_integral.hpp"



#line 5 "tools/is_integral.hpp"

namespace tools {
  template <typename T>
  struct is_integral : std::is_integral<T> {};

  template <typename T>
  inline constexpr bool is_integral_v = tools::is_integral<T>::value;
}


#line 5 "tools/integral.hpp"

namespace tools {
  template <typename T>
  concept integral = tools::is_integral_v<T>;
}


#line 6 "tools/arithmetic.hpp"

namespace tools {
  template <typename T>
  concept arithmetic = tools::integral<T> || std::floating_point<T>;
}


#line 7 "tools/groups.hpp"

namespace tools {
  namespace groups {
    template <typename G>
    struct bit_xor {
      using T = G;
      static T op(const T& x, const T& y) {
        return x ^ y;
      }
      static T e() {
        return T(0);
      }
      static T inv(const T& x) {
        return x;
      }
    };

    template <typename G>
    struct multiplies {
      using T = G;
      static T op(const T& x, const T& y) {
        return x * y;
      }
      static T e() {
        return T(1);
      }
      static T inv(const T& x) {
        return e() / x;
      }
    };

    template <typename G>
    struct plus {
      using T = G;
      static T op(const T& x, const T& y) {
        return x + y;
      }
      static T e() {
        return T(0);
      }
      static T inv(const T& x) {
        return -x;
      }
    };
  }
}


#line 1 "tools/multiplicative_structure.hpp"



#line 1 "lib/ac-library/atcoder/modint.hpp"



#line 5 "lib/ac-library/atcoder/modint.hpp"
#include <numeric>
#line 7 "lib/ac-library/atcoder/modint.hpp"

#ifdef _MSC_VER
#include <intrin.h>
#endif

#line 1 "lib/ac-library/atcoder/internal_math.hpp"



#line 5 "lib/ac-library/atcoder/internal_math.hpp"

#ifdef _MSC_VER
#include <intrin.h>
#endif

namespace atcoder {

namespace internal {

// @param m `1 <= m`
// @return x mod m
constexpr long long safe_mod(long long x, long long m) {
    x %= m;
    if (x < 0) x += m;
    return x;
}

// Fast modular multiplication by barrett reduction
// Reference: https://en.wikipedia.org/wiki/Barrett_reduction
// NOTE: reconsider after Ice Lake
struct barrett {
    unsigned int _m;
    unsigned long long im;

    // @param m `1 <= m`
    explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}

    // @return m
    unsigned int umod() const { return _m; }

    // @param a `0 <= a < m`
    // @param b `0 <= b < m`
    // @return `a * b % m`
    unsigned int mul(unsigned int a, unsigned int b) const {
        // [1] m = 1
        // a = b = im = 0, so okay

        // [2] m >= 2
        // im = ceil(2^64 / m)
        // -> im * m = 2^64 + r (0 <= r < m)
        // let z = a*b = c*m + d (0 <= c, d < m)
        // a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im
        // c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1) < 2^64 * 2
        // ((ab * im) >> 64) == c or c + 1
        unsigned long long z = a;
        z *= b;
#ifdef _MSC_VER
        unsigned long long x;
        _umul128(z, im, &x);
#else
        unsigned long long x =
            (unsigned long long)(((unsigned __int128)(z)*im) >> 64);
#endif
        unsigned long long y = x * _m;
        return (unsigned int)(z - y + (z < y ? _m : 0));
    }
};

// @param n `0 <= n`
// @param m `1 <= m`
// @return `(x ** n) % m`
constexpr long long pow_mod_constexpr(long long x, long long n, int m) {
    if (m == 1) return 0;
    unsigned int _m = (unsigned int)(m);
    unsigned long long r = 1;
    unsigned long long y = safe_mod(x, m);
    while (n) {
        if (n & 1) r = (r * y) % _m;
        y = (y * y) % _m;
        n >>= 1;
    }
    return r;
}

// Reference:
// M. Forisek and J. Jancina,
// Fast Primality Testing for Integers That Fit into a Machine Word
// @param n `0 <= n`
constexpr bool is_prime_constexpr(int n) {
    if (n <= 1) return false;
    if (n == 2 || n == 7 || n == 61) return true;
    if (n % 2 == 0) return false;
    long long d = n - 1;
    while (d % 2 == 0) d /= 2;
    constexpr long long bases[3] = {2, 7, 61};
    for (long long a : bases) {
        long long t = d;
        long long y = pow_mod_constexpr(a, t, n);
        while (t != n - 1 && y != 1 && y != n - 1) {
            y = y * y % n;
            t <<= 1;
        }
        if (y != n - 1 && t % 2 == 0) {
            return false;
        }
    }
    return true;
}
template <int n> constexpr bool is_prime = is_prime_constexpr(n);

// @param b `1 <= b`
// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g
constexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {
    a = safe_mod(a, b);
    if (a == 0) return {b, 0};

    // Contracts:
    // [1] s - m0 * a = 0 (mod b)
    // [2] t - m1 * a = 0 (mod b)
    // [3] s * |m1| + t * |m0| <= b
    long long s = b, t = a;
    long long m0 = 0, m1 = 1;

    while (t) {
        long long u = s / t;
        s -= t * u;
        m0 -= m1 * u;  // |m1 * u| <= |m1| * s <= b

        // [3]:
        // (s - t * u) * |m1| + t * |m0 - m1 * u|
        // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)
        // = s * |m1| + t * |m0| <= b

        auto tmp = s;
        s = t;
        t = tmp;
        tmp = m0;
        m0 = m1;
        m1 = tmp;
    }
    // by [3]: |m0| <= b/g
    // by g != b: |m0| < b/g
    if (m0 < 0) m0 += b / s;
    return {s, m0};
}

// Compile time primitive root
// @param m must be prime
// @return primitive root (and minimum in now)
constexpr int primitive_root_constexpr(int m) {
    if (m == 2) return 1;
    if (m == 167772161) return 3;
    if (m == 469762049) return 3;
    if (m == 754974721) return 11;
    if (m == 998244353) return 3;
    int divs[20] = {};
    divs[0] = 2;
    int cnt = 1;
    int x = (m - 1) / 2;
    while (x % 2 == 0) x /= 2;
    for (int i = 3; (long long)(i)*i <= x; i += 2) {
        if (x % i == 0) {
            divs[cnt++] = i;
            while (x % i == 0) {
                x /= i;
            }
        }
    }
    if (x > 1) {
        divs[cnt++] = x;
    }
    for (int g = 2;; g++) {
        bool ok = true;
        for (int i = 0; i < cnt; i++) {
            if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {
                ok = false;
                break;
            }
        }
        if (ok) return g;
    }
}
template <int m> constexpr int primitive_root = primitive_root_constexpr(m);

// @param n `n < 2^32`
// @param m `1 <= m < 2^32`
// @return sum_{i=0}^{n-1} floor((ai + b) / m) (mod 2^64)
unsigned long long floor_sum_unsigned(unsigned long long n,
                                      unsigned long long m,
                                      unsigned long long a,
                                      unsigned long long b) {
    unsigned long long ans = 0;
    while (true) {
        if (a >= m) {
            ans += n * (n - 1) / 2 * (a / m);
            a %= m;
        }
        if (b >= m) {
            ans += n * (b / m);
            b %= m;
        }

        unsigned long long y_max = a * n + b;
        if (y_max < m) break;
        // y_max < m * (n + 1)
        // floor(y_max / m) <= n
        n = (unsigned long long)(y_max / m);
        b = (unsigned long long)(y_max % m);
        std::swap(m, a);
    }
    return ans;
}

}  // namespace internal

}  // namespace atcoder


#line 1 "lib/ac-library/atcoder/internal_type_traits.hpp"



#line 7 "lib/ac-library/atcoder/internal_type_traits.hpp"

namespace atcoder {

namespace internal {

#ifndef _MSC_VER
template <class T>
using is_signed_int128 =
    typename std::conditional<std::is_same<T, __int128_t>::value ||
                                  std::is_same<T, __int128>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using is_unsigned_int128 =
    typename std::conditional<std::is_same<T, __uint128_t>::value ||
                                  std::is_same<T, unsigned __int128>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using make_unsigned_int128 =
    typename std::conditional<std::is_same<T, __int128_t>::value,
                              __uint128_t,
                              unsigned __int128>;

template <class T>
using is_integral = typename std::conditional<std::is_integral<T>::value ||
                                                  is_signed_int128<T>::value ||
                                                  is_unsigned_int128<T>::value,
                                              std::true_type,
                                              std::false_type>::type;

template <class T>
using is_signed_int = typename std::conditional<(is_integral<T>::value &&
                                                 std::is_signed<T>::value) ||
                                                    is_signed_int128<T>::value,
                                                std::true_type,
                                                std::false_type>::type;

template <class T>
using is_unsigned_int =
    typename std::conditional<(is_integral<T>::value &&
                               std::is_unsigned<T>::value) ||
                                  is_unsigned_int128<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using to_unsigned = typename std::conditional<
    is_signed_int128<T>::value,
    make_unsigned_int128<T>,
    typename std::conditional<std::is_signed<T>::value,
                              std::make_unsigned<T>,
                              std::common_type<T>>::type>::type;

#else

template <class T> using is_integral = typename std::is_integral<T>;

template <class T>
using is_signed_int =
    typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using is_unsigned_int =
    typename std::conditional<is_integral<T>::value &&
                                  std::is_unsigned<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using to_unsigned = typename std::conditional<is_signed_int<T>::value,
                                              std::make_unsigned<T>,
                                              std::common_type<T>>::type;

#endif

template <class T>
using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;

template <class T>
using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;

template <class T> using to_unsigned_t = typename to_unsigned<T>::type;

}  // namespace internal

}  // namespace atcoder


#line 14 "lib/ac-library/atcoder/modint.hpp"

namespace atcoder {

namespace internal {

struct modint_base {};
struct static_modint_base : modint_base {};

template <class T> using is_modint = std::is_base_of<modint_base, T>;
template <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;

}  // namespace internal

template <int m, std::enable_if_t<(1 <= m)>* = nullptr>
struct static_modint : internal::static_modint_base {
    using mint = static_modint;

  public:
    static constexpr int mod() { return m; }
    static mint raw(int v) {
        mint x;
        x._v = v;
        return x;
    }

    static_modint() : _v(0) {}
    template <class T, internal::is_signed_int_t<T>* = nullptr>
    static_modint(T v) {
        long long x = (long long)(v % (long long)(umod()));
        if (x < 0) x += umod();
        _v = (unsigned int)(x);
    }
    template <class T, internal::is_unsigned_int_t<T>* = nullptr>
    static_modint(T v) {
        _v = (unsigned int)(v % umod());
    }

    int val() const { return _v; }

    mint& operator++() {
        _v++;
        if (_v == umod()) _v = 0;
        return *this;
    }
    mint& operator--() {
        if (_v == 0) _v = umod();
        _v--;
        return *this;
    }
    mint operator++(int) {
        mint result = *this;
        ++*this;
        return result;
    }
    mint operator--(int) {
        mint result = *this;
        --*this;
        return result;
    }

    mint& operator+=(const mint& rhs) {
        _v += rhs._v;
        if (_v >= umod()) _v -= umod();
        return *this;
    }
    mint& operator-=(const mint& rhs) {
        _v -= rhs._v;
        if (_v >= umod()) _v += umod();
        return *this;
    }
    mint& operator*=(const mint& rhs) {
        unsigned long long z = _v;
        z *= rhs._v;
        _v = (unsigned int)(z % umod());
        return *this;
    }
    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }

    mint operator+() const { return *this; }
    mint operator-() const { return mint() - *this; }

    mint pow(long long n) const {
        assert(0 <= n);
        mint x = *this, r = 1;
        while (n) {
            if (n & 1) r *= x;
            x *= x;
            n >>= 1;
        }
        return r;
    }
    mint inv() const {
        if (prime) {
            assert(_v);
            return pow(umod() - 2);
        } else {
            auto eg = internal::inv_gcd(_v, m);
            assert(eg.first == 1);
            return eg.second;
        }
    }

    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;
    }

  private:
    unsigned int _v;
    static constexpr unsigned int umod() { return m; }
    static constexpr bool prime = internal::is_prime<m>;
};

template <int id> struct dynamic_modint : internal::modint_base {
    using mint = dynamic_modint;

  public:
    static int mod() { return (int)(bt.umod()); }
    static void set_mod(int m) {
        assert(1 <= m);
        bt = internal::barrett(m);
    }
    static mint raw(int v) {
        mint x;
        x._v = v;
        return x;
    }

    dynamic_modint() : _v(0) {}
    template <class T, internal::is_signed_int_t<T>* = nullptr>
    dynamic_modint(T v) {
        long long x = (long long)(v % (long long)(mod()));
        if (x < 0) x += mod();
        _v = (unsigned int)(x);
    }
    template <class T, internal::is_unsigned_int_t<T>* = nullptr>
    dynamic_modint(T v) {
        _v = (unsigned int)(v % mod());
    }

    int val() const { return _v; }

    mint& operator++() {
        _v++;
        if (_v == umod()) _v = 0;
        return *this;
    }
    mint& operator--() {
        if (_v == 0) _v = umod();
        _v--;
        return *this;
    }
    mint operator++(int) {
        mint result = *this;
        ++*this;
        return result;
    }
    mint operator--(int) {
        mint result = *this;
        --*this;
        return result;
    }

    mint& operator+=(const mint& rhs) {
        _v += rhs._v;
        if (_v >= umod()) _v -= umod();
        return *this;
    }
    mint& operator-=(const mint& rhs) {
        _v += mod() - rhs._v;
        if (_v >= umod()) _v -= umod();
        return *this;
    }
    mint& operator*=(const mint& rhs) {
        _v = bt.mul(_v, rhs._v);
        return *this;
    }
    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }

    mint operator+() const { return *this; }
    mint operator-() const { return mint() - *this; }

    mint pow(long long n) const {
        assert(0 <= n);
        mint x = *this, r = 1;
        while (n) {
            if (n & 1) r *= x;
            x *= x;
            n >>= 1;
        }
        return r;
    }
    mint inv() const {
        auto eg = internal::inv_gcd(_v, mod());
        assert(eg.first == 1);
        return eg.second;
    }

    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;
    }

  private:
    unsigned int _v;
    static internal::barrett bt;
    static unsigned int umod() { return bt.umod(); }
};
template <int id> internal::barrett dynamic_modint<id>::bt(998244353);

using modint998244353 = static_modint<998244353>;
using modint1000000007 = static_modint<1000000007>;
using modint = dynamic_modint<-1>;

namespace internal {

template <class T>
using is_static_modint = std::is_base_of<internal::static_modint_base, T>;

template <class T>
using is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;

template <class> struct is_dynamic_modint : public std::false_type {};
template <int id>
struct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};

template <class T>
using is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;

}  // namespace internal

}  // namespace atcoder


#line 1 "tools/complex.hpp"



#include <complex>
#line 1 "tools/specialization_of.hpp"



#line 5 "tools/specialization_of.hpp"

namespace tools {
  namespace detail {
    namespace specialization_of {
      template <typename, template <typename...> typename>
      struct trait : std::false_type {};

      template <template <typename...> typename U, typename... Args>
      struct trait<U<Args...>, U> : std::true_type {};
    }
  }

  template <typename T, template <typename...> typename U>
  concept specialization_of = tools::detail::specialization_of::trait<T, U>::value;
}


#line 6 "tools/complex.hpp"

namespace tools {
  template <typename T>
  concept complex = tools::specialization_of<T, std::complex>;
}


#line 1 "tools/is_prime.hpp"



#line 1 "tools/prod_mod.hpp"



#line 1 "tools/uint128_t.hpp"



#line 1 "tools/detail/int128_t_and_uint128_t.hpp"



#line 8 "tools/detail/int128_t_and_uint128_t.hpp"
#include <functional>
#line 12 "tools/detail/int128_t_and_uint128_t.hpp"
#include <string_view>
#line 1 "tools/abs.hpp"



#include <cmath>
#line 7 "tools/abs.hpp"

namespace tools {
  namespace detail::abs {
    template <typename T>
    struct impl {
      constexpr decltype(auto) operator()(const T x) const noexcept(noexcept(std::abs(x))) {
        return std::abs(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) abs(T&& x) noexcept(noexcept(tools::detail::abs::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::abs::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/bit_ceil.hpp"



#include <bit>
#line 1 "tools/is_signed.hpp"



#line 5 "tools/is_signed.hpp"

namespace tools {
  template <typename T>
  struct is_signed : std::is_signed<T> {};

  template <typename T>
  inline constexpr bool is_signed_v = tools::is_signed<T>::value;
}


#line 1 "tools/is_unsigned.hpp"



#line 5 "tools/is_unsigned.hpp"

namespace tools {
  template <typename T>
  struct is_unsigned : std::is_unsigned<T> {};

  template <typename T>
  inline constexpr bool is_unsigned_v = tools::is_unsigned<T>::value;
}


#line 1 "tools/make_unsigned.hpp"



#line 5 "tools/make_unsigned.hpp"

namespace tools {
  template <typename T>
  struct make_unsigned : std::make_unsigned<T> {};

  template <typename T>
  using make_unsigned_t = typename tools::make_unsigned<T>::type;
}


#line 1 "tools/non_bool_integral.hpp"



#line 7 "tools/non_bool_integral.hpp"

namespace tools {
  template <typename T>
  concept non_bool_integral = tools::integral<T> && !std::same_as<std::remove_cv_t<T>, bool>;
}


#line 12 "tools/bit_ceil.hpp"

namespace tools {
  namespace detail::bit_ceil {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr T operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr T operator()(const T x) const noexcept(noexcept(std::bit_ceil(x))) requires tools::is_unsigned_v<T> {
        return std::bit_ceil(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) bit_ceil(T&& x) noexcept(noexcept(tools::detail::bit_ceil::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::bit_ceil::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/bit_floor.hpp"



#line 12 "tools/bit_floor.hpp"

namespace tools {
  namespace detail::bit_floor {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr T operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr T operator()(const T x) const noexcept(noexcept(std::bit_floor(x))) requires tools::is_unsigned_v<T> {
        return std::bit_floor(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) bit_floor(T&& x) noexcept(noexcept(tools::detail::bit_floor::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::bit_floor::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/bit_width.hpp"



#line 12 "tools/bit_width.hpp"

namespace tools {
  namespace detail::bit_width {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr int operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr int operator()(const T x) const noexcept(noexcept(std::bit_width(x))) requires tools::is_unsigned_v<T> {
        return std::bit_width(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) bit_width(T&& x) noexcept(noexcept(tools::detail::bit_width::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::bit_width::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/countr_zero.hpp"



#line 14 "tools/countr_zero.hpp"

namespace tools {
  namespace detail::countr_zero {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr int operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return std::min(impl<tools::make_unsigned_t<T>>{}(x), std::numeric_limits<T>::digits);
      }
      constexpr int operator()(const T x) const noexcept(noexcept(std::countr_zero(x))) requires tools::is_unsigned_v<T> {
        return std::countr_zero(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) countr_zero(T&& x) noexcept(noexcept(tools::detail::countr_zero::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::countr_zero::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/gcd.hpp"



#line 7 "tools/gcd.hpp"

namespace tools {
  namespace detail::gcd {
    template <typename M, typename N>
    struct impl {
      constexpr decltype(auto) operator()(const M m, const N n) const noexcept(noexcept(std::gcd(m, n))) {
        return std::gcd(m, n);
      }
    };
  }

  template <typename M, typename N>
  constexpr decltype(auto) gcd(M&& m, N&& n) noexcept(noexcept(tools::detail::gcd::impl<std::remove_cvref_t<M>, std::remove_cvref_t<N>>{}(std::forward<M>(m), std::forward<N>(n)))) {
    return tools::detail::gcd::impl<std::remove_cvref_t<M>, std::remove_cvref_t<N>>{}(std::forward<M>(m), std::forward<N>(n));
  }
}


#line 1 "tools/has_single_bit.hpp"



#line 12 "tools/has_single_bit.hpp"

namespace tools {
  namespace detail::has_single_bit {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr bool operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr bool operator()(const T x) const noexcept(noexcept(std::has_single_bit(x))) requires tools::is_unsigned_v<T> {
        return std::has_single_bit(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) has_single_bit(T&& x) noexcept(noexcept(tools::detail::has_single_bit::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::has_single_bit::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/hash_combine.hpp"



#line 6 "tools/hash_combine.hpp"

// Source: https://github.com/google/cityhash/blob/f5dc54147fcce12cefd16548c8e760d68ac04226/src/city.h
// License: MIT
// Author: Google Inc.

// Copyright (c) 2011 Google, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

namespace tools {
  template <typename T>
  void hash_combine(std::size_t& seed, const T& v) {
    static const std::hash<T> hasher;
    static constexpr std::size_t k_mul = 0x9ddfea08eb382d69ULL;
    std::size_t a = (hasher(v) ^ seed) * k_mul;
    a ^= (a >> 47);
    std::size_t b = (seed ^ a) * k_mul;
    b ^= (b >> 47);
    seed = b * k_mul;
  }
}


#line 1 "tools/make_signed.hpp"



#line 5 "tools/make_signed.hpp"

namespace tools {
  template <typename T>
  struct make_signed : std::make_signed<T> {};

  template <typename T>
  using make_signed_t = typename tools::make_signed<T>::type;
}


#line 1 "tools/now.hpp"



#include <chrono>

namespace tools {
  inline long long now() {
    return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
  }
}


#line 1 "tools/popcount.hpp"



#line 12 "tools/popcount.hpp"

namespace tools {
  namespace detail::popcount {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr int operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr int operator()(const T x) const noexcept(noexcept(std::popcount(x))) requires tools::is_unsigned_v<T> {
        return std::popcount(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) popcount(T&& x) noexcept(noexcept(tools::detail::popcount::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::popcount::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 31 "tools/detail/int128_t_and_uint128_t.hpp"

namespace tools {
  using uint128_t = unsigned __int128;
  using int128_t = __int128;

  template <>
  struct is_integral<tools::int128_t> : std::true_type {};
  template <>
  struct is_integral<tools::uint128_t> : std::true_type {};
  template <>
  struct is_integral<const tools::int128_t> : std::true_type {};
  template <>
  struct is_integral<const tools::uint128_t> : std::true_type {};
  template <>
  struct is_integral<volatile tools::int128_t> : std::true_type {};
  template <>
  struct is_integral<volatile tools::uint128_t> : std::true_type {};
  template <>
  struct is_integral<const volatile tools::int128_t> : std::true_type {};
  template <>
  struct is_integral<const volatile tools::uint128_t> : std::true_type {};

  template <>
  struct is_signed<tools::int128_t> : std::true_type {};
  template <>
  struct is_signed<tools::uint128_t> : std::false_type {};
  template <>
  struct is_signed<const tools::int128_t> : std::true_type {};
  template <>
  struct is_signed<const tools::uint128_t> : std::false_type {};
  template <>
  struct is_signed<volatile tools::int128_t> : std::true_type {};
  template <>
  struct is_signed<volatile tools::uint128_t> : std::false_type {};
  template <>
  struct is_signed<const volatile tools::int128_t> : std::true_type {};
  template <>
  struct is_signed<const volatile tools::uint128_t> : std::false_type {};

  template <>
  struct is_unsigned<tools::int128_t> : std::false_type {};
  template <>
  struct is_unsigned<tools::uint128_t> : std::true_type {};
  template <>
  struct is_unsigned<const tools::int128_t> : std::false_type {};
  template <>
  struct is_unsigned<const tools::uint128_t> : std::true_type {};
  template <>
  struct is_unsigned<volatile tools::int128_t> : std::false_type {};
  template <>
  struct is_unsigned<volatile tools::uint128_t> : std::true_type {};
  template <>
  struct is_unsigned<const volatile tools::int128_t> : std::false_type {};
  template <>
  struct is_unsigned<const volatile tools::uint128_t> : std::true_type {};

  template <>
  struct make_signed<tools::int128_t> {
    using type = tools::int128_t;
  };
  template <>
  struct make_signed<tools::uint128_t> {
    using type = tools::int128_t;
  };
  template <>
  struct make_signed<const tools::int128_t> {
    using type = const tools::int128_t;
  };
  template <>
  struct make_signed<const tools::uint128_t> {
    using type = const tools::int128_t;
  };
  template <>
  struct make_signed<volatile tools::int128_t> {
    using type = volatile tools::int128_t;
  };
  template <>
  struct make_signed<volatile tools::uint128_t> {
    using type = volatile tools::int128_t;
  };
  template <>
  struct make_signed<const volatile tools::int128_t> {
    using type = const volatile tools::int128_t;
  };
  template <>
  struct make_signed<const volatile tools::uint128_t> {
    using type = const volatile tools::int128_t;
  };

  template <>
  struct make_unsigned<tools::int128_t> {
    using type = tools::uint128_t;
  };
  template <>
  struct make_unsigned<tools::uint128_t> {
    using type = tools::uint128_t;
  };
  template <>
  struct make_unsigned<const tools::int128_t> {
    using type = const tools::uint128_t;
  };
  template <>
  struct make_unsigned<const tools::uint128_t> {
    using type = const tools::uint128_t;
  };
  template <>
  struct make_unsigned<volatile tools::int128_t> {
    using type = volatile tools::uint128_t;
  };
  template <>
  struct make_unsigned<volatile tools::uint128_t> {
    using type = volatile tools::uint128_t;
  };
  template <>
  struct make_unsigned<const volatile tools::int128_t> {
    using type = const volatile tools::uint128_t;
  };
  template <>
  struct make_unsigned<const volatile tools::uint128_t> {
    using type = const volatile tools::uint128_t;
  };

  namespace detail::int128_t {
    constexpr tools::uint128_t parse_unsigned(const std::string_view s) noexcept {
      assert(!s.empty());
      tools::uint128_t x = 0;
      std::size_t i = s[0] == '+';
      if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
        for (i += 2; i < s.size(); ++i) {
          assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
          x <<= 4;
          if ('0' <= s[i] && s[i] <= '9') {
            x |= s[i] - '0';
          } else if ('a' <= s[i] && s[i] <= 'f') {
            x |= s[i] - 'a' + 10;
          } else {
            x |= s[i] - 'A' + 10;
          }
        }
      } else {
        for (; i < s.size(); ++i) {
          assert('0' <= s[i] && s[i] <= '9');
          x *= 10;
          x += s[i] - '0';
        }
      }
      return x;
    }

    constexpr tools::int128_t parse_signed(const std::string_view s) noexcept {
      assert(!s.empty());
      tools::int128_t x = 0;
      if (s[0] == '-') {
        std::size_t i = 1;
        if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
          for (i += 2; i < s.size(); ++i) {
            assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
            x *= 16;
            if ('0' <= s[i] && s[i] <= '9') {
              x -= s[i] - '0';
            } else if ('a' <= s[i] && s[i] <= 'f') {
              x -= s[i] - 'a' + 10;
            } else {
              x -= s[i] - 'A' + 10;
            }
          }
        } else {
          for (; i < s.size(); ++i) {
            assert('0' <= s[i] && s[i] <= '9');
            x *= 10;
            x -= s[i] - '0';
          }
        }
      } else {
        std::size_t i = s[0] == '+';
        if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
          for (i += 2; i < s.size(); ++i) {
            assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
            x <<= 4;
            if ('0' <= s[i] && s[i] <= '9') {
              x |= s[i] - '0';
            } else if ('a' <= s[i] && s[i] <= 'f') {
              x |= s[i] - 'a' + 10;
            } else {
              x |= s[i] - 'A' + 10;
            }
          }
        } else {
          for (; i < s.size(); ++i) {
            assert('0' <= s[i] && s[i] <= '9');
            x *= 10;
            x += s[i] - '0';
          }
        }
      }
      return x;
    }
  }
}

#define UINT128_C(c) tools::detail::int128_t::parse_unsigned(#c)
#define INT128_C(c) tools::detail::int128_t::parse_signed(#c)

inline std::istream& operator>>(std::istream& is, tools::uint128_t& x) {
  std::string s;
  is >> s;
  x = tools::detail::int128_t::parse_unsigned(s);
  return is;
}
inline std::istream& operator>>(std::istream& is, tools::int128_t& x) {
  std::string s;
  is >> s;
  x = tools::detail::int128_t::parse_signed(s);
  return is;
}

inline std::ostream& operator<<(std::ostream& os, tools::uint128_t x) {
  std::string s;
  if (x > 0) {
    while (x > 0) {
      s.push_back('0' + x % 10);
      x /= 10;
    }
  } else {
    s.push_back('0');
  }

  std::ranges::reverse(s);
  return os << s;
}
inline std::ostream& operator<<(std::ostream& os, tools::int128_t x) {
  std::string s;
  if (x > 0) {
    while (x > 0) {
      s.push_back('0' + x % 10);
      x /= 10;
    }
  } else if (x < 0) {
    while (x < 0) {
      s.push_back('0' + (-(x % 10)));
      x /= 10;
    }
    s.push_back('-');
  } else {
    s.push_back('0');
  }

  std::ranges::reverse(s);
  return os << s;
}

#if defined(__GLIBCXX__) && defined(__STRICT_ANSI__)
namespace std {
  template <>
  struct hash<tools::uint128_t> {
    std::size_t operator()(const tools::uint128_t& x) const {
      static const std::size_t seed = tools::now();

      std::size_t hash = seed;
      tools::hash_combine(hash, static_cast<std::uint64_t>(x >> 64));
      tools::hash_combine(hash, static_cast<std::uint64_t>(x & ((UINT128_C(1) << 64) - 1)));
      return hash;
    }
  };
  template <>
  struct hash<tools::int128_t> {
    std::size_t operator()(const tools::int128_t& x) const {
      static std::hash<tools::uint128_t> hasher;
      return hasher(static_cast<tools::uint128_t>(x));
    }
  };
}
#endif

namespace tools {
  template <>
  struct detail::abs::impl<tools::int128_t> {
    constexpr tools::int128_t operator()(const tools::int128_t& x) const noexcept {
      return x >= 0 ? x : -x;
    }
  };

#if defined(__GLIBCXX__) && defined(__STRICT_ANSI__)
  template <>
  struct detail::bit_ceil::impl<tools::uint128_t> {
    constexpr tools::uint128_t operator()(tools::uint128_t x) const noexcept {
      if (x <= 1) return 1;
      --x;
      x |= x >> 1;
      x |= x >> 2;
      x |= x >> 4;
      x |= x >> 8;
      x |= x >> 16;
      x |= x >> 32;
      x |= x >> 64;
      return ++x;
    }
  };

  template <>
  struct detail::bit_floor::impl<tools::uint128_t> {
    constexpr tools::uint128_t operator()(tools::uint128_t x) const noexcept {
      x |= x >> 1;
      x |= x >> 2;
      x |= x >> 4;
      x |= x >> 8;
      x |= x >> 16;
      x |= x >> 32;
      x |= x >> 64;
      return x & ~(x >> 1);
    }
  };

  template <>
  struct detail::bit_width::impl<tools::uint128_t> {
    constexpr int operator()(tools::uint128_t x) const noexcept {
      int w = 0;
      if (x & UINT128_C(0xffffffffffffffff0000000000000000)) {
        x >>= 64;
        w += 64;
      }
      if (x & UINT128_C(0xffffffff00000000)) {
        x >>= 32;
        w += 32;
      }
      if (x & UINT128_C(0xffff0000)) {
        x >>= 16;
        w += 16;
      }
      if (x & UINT128_C(0xff00)) {
        x >>= 8;
        w += 8;
      }
      if (x & UINT128_C(0xf0)) {
        x >>= 4;
        w += 4;
      }
      if (x & UINT128_C(0xc)) {
        x >>= 2;
        w += 2;
      }
      if (x & UINT128_C(0x2)) {
        x >>= 1;
        w += 1;
      }
      w += x;
      return w;
    }
  };

  template <>
  class detail::countr_zero::impl<tools::uint128_t> {
    using type = tools::uint128_t;
    static constexpr int shift = 120;
    static constexpr type magic = UINT128_C(0x01061438916347932a5cd9d3ead7b77f);
    static constexpr int ntz_table[255] = {
      128,   0,   1,  -1,   2,  -1,   8,  -1,   3,  -1,  15,  -1,   9,  -1,  22,  -1,
        4,  -1,  29,  -1,  16,  -1,  36,  -1,  10,  -1,  43,  -1,  23,  -1,  50,  -1,
        5,  -1,  33,  -1,  30,  -1,  57,  -1,  17,  -1,  64,  -1,  37,  -1,  71,  -1,
       11,  -1,  60,  -1,  44,  -1,  78,  -1,  24,  -1,  85,  -1,  51,  -1,  92,  -1,
       -1,   6,  -1,  20,  -1,  34,  -1,  48,  31,  -1,  -1,  69,  58,  -1,  -1,  90,
       18,  -1,  67,  -1,  65,  -1,  99,  -1,  38,  -1, 101,  -1,  72,  -1, 106,  -1,
       -1,  12,  -1,  40,  -1,  61,  -1,  82,  45,  -1,  -1, 103,  79,  -1, 113,  -1,
       -1,  25,  -1,  74,  86,  -1,  -1, 116,  -1,  52,  -1, 108,  -1,  93,  -1, 120,
      127,  -1,  -1,   7,  -1,  14,  -1,  21,  -1,  28,  -1,  35,  -1,  42,  -1,  49,
       -1,  32,  -1,  56,  -1,  63,  -1,  70,  -1,  59,  -1,  77,  -1,  84,  -1,  91,
       -1,  19,  -1,  47,  -1,  68,  -1,  89,  -1,  66,  -1,  98,  -1, 100,  -1, 105,
       -1,  39,  -1,  81,  -1, 102,  -1, 112,  -1,  73,  -1, 115,  -1, 107,  -1, 119,
      126,  -1,  13,  -1,  27,  -1,  41,  -1,  -1,  55,  62,  -1,  -1,  76,  83,  -1,
       -1,  46,  -1,  88,  -1,  97,  -1, 104,  -1,  80,  -1, 111,  -1, 114,  -1, 118,
      125,  -1,  26,  -1,  54,  -1,  75,  -1,  -1,  87,  96,  -1,  -1, 110,  -1, 117,
      124,  -1,  53,  -1,  -1,  95, 109,  -1, 123,  -1,  94,  -1, 122,  -1, 121
    };

  public:
    constexpr int operator()(const type& x) const noexcept {
      return ntz_table[static_cast<type>(magic * static_cast<type>(x & -x)) >> shift];
    }
  };

  namespace detail::gcd {
    template <>
    struct impl<tools::uint128_t, tools::uint128_t> {
      constexpr tools::uint128_t operator()(tools::uint128_t m, tools::uint128_t n) const noexcept {
        while (n != 0) {
          m %= n;
          std::swap(m, n);
        }
        return m;
      };
    };

    template <typename T>
    concept non_bool_integral_at_most_128bit = tools::non_bool_integral<T> && std::numeric_limits<T>::digits <= 128;
    template <typename T>
    concept non_bool_integral_at_most_64bit = tools::non_bool_integral<T> && std::numeric_limits<T>::digits <= 64;

    template <typename M, typename N> requires (
      (non_bool_integral_at_most_128bit<M> && non_bool_integral_at_most_128bit<N>)
      && !(non_bool_integral_at_most_64bit<M> && non_bool_integral_at_most_64bit<N>)
      && !(std::same_as<M, tools::uint128_t> && std::same_as<N, tools::uint128_t>)
    )
    struct impl<M, N> {
      constexpr std::common_type_t<M, N> operator()(const M m, const N n) const noexcept {
        return std::common_type_t<M, N>(
          tools::gcd(
            m >= 0 ? tools::uint128_t(m) : tools::uint128_t(-(m + 1)) + 1,
            n >= 0 ? tools::uint128_t(n) : tools::uint128_t(-(n + 1)) + 1
          )
        );
      }
    };
  }

  template <>
  struct detail::has_single_bit::impl<tools::uint128_t> {
    constexpr bool operator()(tools::uint128_t x) const noexcept {
      return x != 0 && (x & (x - 1)) == 0;
    }
  };

  template <>
  struct detail::popcount::impl<tools::uint128_t> {
    constexpr int operator()(tools::uint128_t x) const noexcept {
      x = (x & UINT128_C(0x55555555555555555555555555555555)) + (x >> 1 & UINT128_C(0x55555555555555555555555555555555));
      x = (x & UINT128_C(0x33333333333333333333333333333333)) + (x >> 2 & UINT128_C(0x33333333333333333333333333333333));
      x = (x & UINT128_C(0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f)) + (x >> 4 & UINT128_C(0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f));
      x = (x & UINT128_C(0x00ff00ff00ff00ff00ff00ff00ff00ff)) + (x >> 8 & UINT128_C(0x00ff00ff00ff00ff00ff00ff00ff00ff));
      x = (x & UINT128_C(0x0000ffff0000ffff0000ffff0000ffff)) + (x >> 16 & UINT128_C(0x0000ffff0000ffff0000ffff0000ffff));
      x = (x & UINT128_C(0x00000000ffffffff00000000ffffffff)) + (x >> 32 & UINT128_C(0x00000000ffffffff00000000ffffffff));
      x = (x & UINT128_C(0x0000000000000000ffffffffffffffff)) + (x >> 64 & UINT128_C(0x0000000000000000ffffffffffffffff));
      return x;
    }
  };
#endif
}


#line 5 "tools/uint128_t.hpp"


#line 5 "tools/prod_mod.hpp"

namespace tools {

  template <typename T1, typename T2, typename T3>
  constexpr T3 prod_mod(const T1 x, const T2 y, const T3 m) {
    using u128 = tools::uint128_t;
    u128 prod_mod = u128(x >= 0 ? x : -x) * u128(y >= 0 ? y : -y) % u128(m);
    if ((x >= 0) ^ (y >= 0)) prod_mod = u128(m) - prod_mod;
    return prod_mod;
  }
}


#line 1 "tools/pow_mod.hpp"



#line 1 "tools/mod.hpp"



#line 7 "tools/mod.hpp"

namespace tools {
  template <tools::non_bool_integral M, tools::non_bool_integral N>
  constexpr std::common_type_t<M, N> mod(const M a, const N b) noexcept {
    assert(b != 0);

    using UM = tools::make_unsigned_t<M>;
    using UN = tools::make_unsigned_t<N>;
    const UM ua = a >= 0 ? a : static_cast<UM>(-(a + 1)) + 1;
    const UN ub = b >= 0 ? b : static_cast<UN>(-(b + 1)) + 1;
    auto r = ua % ub;
    if (a < 0 && r > 0) {
      r = ub - r;
    }
    return r;
  }
}


#line 6 "tools/pow_mod.hpp"

namespace tools {

  template <typename T1, typename T2, typename T3>
  constexpr T3 pow_mod(const T1 x, T2 n, const T3 m) {
    if (m == 1) return 0;
    T3 r = 1;
    T3 y = tools::mod(x, m);
    while (n > 0) {
      if ((n & 1) > 0) {
        r = tools::prod_mod(r, y, m);
      }
      y = tools::prod_mod(y, y, m);
      n /= 2;
    }
    return r;
  }
}


#line 7 "tools/is_prime.hpp"

namespace tools {

  constexpr bool is_prime(const unsigned long long n) {
    constexpr std::array<unsigned long long, 7> bases = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};

    if (n <= 1) return false;
    if (n == 2) return true;
    if (n % 2 == 0) return false;

    auto d = n - 1;
    for (; d % 2 == 0; d /= 2);

    for (const auto a : bases) {
      if (a % n == 0) return true;

      auto power = d;
      auto target = tools::pow_mod(a, power, n);

      bool is_composite = true;
      if (target == 1) is_composite = false;
      for (; is_composite && power != n - 1; power *= 2, target = tools::prod_mod(target, target, n)) {
        if (target == n - 1) is_composite = false;
      }

      if (is_composite) {
        return false;
      }
    }

    return true;
  }
}


#line 1 "tools/monoids.hpp"



#line 14 "tools/monoids.hpp"

namespace tools {
  namespace monoids {
    template <typename M>
    struct bit_and {
      using T = M;
      static T op(const T& x, const T& y) {
        return x & y;
      }
      static T e() {
        return std::numeric_limits<T>::max();
      }
    };

    template <typename M>
    struct bit_or {
      using T = M;
      static T op(const T& x, const T& y) {
        return x | y;
      }
      static T e() {
        return T(0);
      }
    };

    template <typename M>
    requires requires (M x, M y) {
      {tools::gcd(x, y)} -> std::convertible_to<M>;
    }
    struct gcd {
      using T = M;
      static T op(const T& x, const T& y) {
        return tools::gcd(x, y);
      }
      static T e() {
        return T(0);
      }
    };

    template <typename M, M ...dummy>
    struct max;

    template <tools::arithmetic M>
    struct max<M> {
      using T = M;
      static T op(const T& x, const T& y) {
        return std::max(x, y);
      }
      static T e() {
        if constexpr (tools::integral<M>) {
          return std::numeric_limits<M>::min();
        } else {
          return -std::numeric_limits<M>::infinity();
        }
      }
    };

    template <std::totally_ordered M, M E>
    struct max<M, E> {
      using T = M;
      static T op(const T& x, const T& y) {
        assert(E <= x);
        assert(E <= y);
        return std::max(x, y);
      }
      static T e() {
        return E;
      }
    };

    template <typename M, M ...dummy>
    struct min;

    template <tools::arithmetic M>
    struct min<M> {
      using T = M;
      static T op(const T& x, const T& y) {
        return std::min(x, y);
      }
      static T e() {
        if constexpr (tools::integral<M>) {
          return std::numeric_limits<M>::max();
        } else {
          return std::numeric_limits<M>::infinity();
        }
      }
    };

    template <std::totally_ordered M, M E>
    struct min<M, E> {
      using T = M;
      static T op(const T& x, const T& y) {
        assert(x <= E);
        assert(y <= E);
        return std::min(x, y);
      }
      static T e() {
        return E;
      }
    };

    template <typename M>
    struct multiplies {
      using T = M;
      static T op(const T& x, const T& y) {
        return x * y;
      }
      static T e() {
        return T(1);
      }
    };

    template <>
    struct multiplies<bool> {
      using T = bool;
      static T op(const bool x, const bool y) {
        return x && y;
      }
      static T e() {
        return true;
      }
    };

    template <typename M, M E>
    struct update {
      using T = M;
      static T op(const T& x, const T& y) {
        return x == E ? y : x;
      }
      static T e() {
        return E;
      }
    };
  }
}


#line 1 "tools/prime_static_modint.hpp"



#line 6 "tools/prime_static_modint.hpp"

namespace tools {
  template <typename T>
  concept prime_static_modint = atcoder::internal::is_static_modint<T>::value && tools::is_prime(T::mod());
}


#line 13 "tools/multiplicative_structure.hpp"

namespace tools {
  template <typename T>
  using multiplicative_structure = std::conditional_t<
    tools::complex<T> || std::floating_point<T> || tools::prime_static_modint<T> || atcoder::internal::is_dynamic_modint<T>::value,
      tools::groups::multiplies<T>,
      std::conditional_t<
        tools::integral<T> || atcoder::internal::is_static_modint<T>::value,
          tools::monoids::multiplies<T>,
          std::conditional_t<
            requires(T a, T b) { { a / b } -> std::same_as<T>; },
              tools::groups::multiplies<T>,
              tools::monoids::multiplies<T>
          >
      >
  >;
}


#line 1 "tools/mutable_type.hpp"



#line 5 "tools/mutable_type.hpp"

namespace tools {
  template <typename T>
  concept mutable_type = !std::is_const_v<std::remove_reference_t<T>>;
}


#line 1 "tools/rings.hpp"



#line 1 "tools/semirings.hpp"



#line 8 "tools/semirings.hpp"

namespace tools {
  namespace semirings {
    template <tools::commutative_monoid A, tools::monoid M>
    struct of {
      using add = A;
      using mul = M;
    };

    template <typename R>
    using min_plus = tools::semirings::of<tools::monoids::min<R>, tools::groups::plus<R>>;

    template <typename R>
    using max_plus = tools::semirings::of<tools::monoids::max<R>, tools::groups::plus<R>>;

    template <typename R>
    using min_max = tools::semirings::of<tools::monoids::min<R>, tools::monoids::max<R>>;

    template <typename R>
    using max_min = tools::semirings::of<tools::monoids::max<R>, tools::monoids::min<R>>;
  }
}


#line 9 "tools/rings.hpp"

namespace tools {
  namespace rings {
    template <tools::commutative_group A, tools::monoid M>
    using of = tools::semirings::of<A, M>;

    template <typename R>
    using plus_multiplies = tools::rings::of<tools::groups::plus<R>, tools::monoids::multiplies<R>>;

    template <typename R>
    using xor_and = tools::rings::of<tools::groups::bit_xor<R>, tools::monoids::bit_and<R>>;
  }
}


#line 1 "tools/vector.hpp"



#line 16 "tools/vector.hpp"
#include <tuple>
#line 1 "tools/tuple_hash.hpp"



#line 11 "tools/tuple_hash.hpp"

namespace tools {
  template <typename... Ts>
  struct tuple_hash {
    template <std::size_t I = sizeof...(Ts) - 1>
    std::size_t operator()(const std::tuple<Ts...>& key) const {
      if constexpr (I == std::numeric_limits<std::size_t>::max()) {
        static const std::size_t seed = tools::now();
        return seed;
      } else {
        std::size_t seed = this->operator()<I - 1>(key);
        tools::hash_combine(seed, std::get<I>(key));
        return seed;
      }
    }
  };
}


#line 22 "tools/vector.hpp"

namespace tools {
  namespace detail {
    namespace vector {
      template <typename T, std::size_t N>
      class members {
      protected:
        constexpr static bool variable_sized = false;
        constexpr static bool has_aliases = false;
        std::array<T, N> m_values;
        members() : m_values() {}
        members(const std::initializer_list<T> il) : m_values(il) {
          assert(il.size() == N);
        }
      };

      template <typename T>
      class members<T, 2> {
      protected:
        constexpr static bool variable_sized = false;
        constexpr static bool has_aliases = true;
        members() = default;
        members(const T& x, const T& y) : x(x), y(y) {}
        members(const std::initializer_list<T> il) : x(il.begin()[0]), y(il.begin()[1]) {
          assert(il.size() == 2);
        }

      public:
        T x;
        T y;
      };

      template <typename T>
      class members<T, 3> {
      protected:
        constexpr static bool variable_sized = false;
        constexpr static bool has_aliases = true;
        members() = default;
        members(const T& x, const T& y, const T& z) : x(x), y(y), z(z) {}
        members(const std::initializer_list<T> il) : x(il.begin()[0]), y(il.begin()[1]), z(il.begin()[2]) {
          assert(il.size() == 3);
        }

      public:
        T x;
        T y;
        T z;
      };

      template <typename T>
      class members<T, 4> {
      protected:
        constexpr static bool variable_sized = false;
        constexpr static bool has_aliases = true;
        members() = default;
        members(const T& x, const T& y, const T& z, const T& w) : x(x), y(y), z(z), w(w) {}
        members(const std::initializer_list<T> il) : x(il.begin()[0]), y(il.begin()[1]), z(il.begin()[2]), w(il.begin()[3]) {
          assert(il.size() == 4);
        }

      public:
        T x;
        T y;
        T z;
        T w;
      };

      template <typename T>
      class members<T, std::numeric_limits<std::size_t>::max()> {
      protected:
        constexpr static bool variable_sized = true;
        constexpr static bool has_aliases = false;
        std::vector<T> m_values;
        members() = default;
        members(const std::size_t n) : m_values(n) {}
        members(const std::size_t n, const T& value) : m_values(n, value) {}
        template <std::input_iterator InputIter>
        members(const InputIter first, const InputIter last) : m_values(first, last) {}
        members(const std::initializer_list<T> il) : m_values(il) {}
      };
    }
  }

  template <typename T, std::size_t N = std::numeric_limits<std::size_t>::max()>
  class vector : public tools::detail::vector::members<T, N> {
    using Base = tools::detail::vector::members<T, N>;
    using F = std::conditional_t<std::floating_point<T>, T, double>;
    using V = tools::vector<T, N>;
    constexpr static bool variable_sized = Base::variable_sized;
    constexpr static bool has_aliases = Base::has_aliases;

  public:
    using reference = T&;
    using const_reference = const T&;
    using size_type = std::size_t;
    using difference_type = std::ptrdiff_t;
    using pointer = T*;
    using const_pointer = const T*;
    using value_type = T;
    class iterator {
      V* m_parent;
      size_type m_i;

    public:
      using difference_type = std::ptrdiff_t;
      using value_type = T;
      using reference = T&;
      using pointer = T*;
      using iterator_category = std::random_access_iterator_tag;

      iterator() = default;
      iterator(V * const parent, const size_type i) : m_parent(parent), m_i(i) {}

      reference operator*() const {
        return (*this->m_parent)[this->m_i];
      }
      pointer operator->() const {
        return &(*(*this));
      }

      iterator& operator++() {
        ++this->m_i;
        return *this;
      }
      iterator operator++(int) {
        const auto self = *this;
        ++*this;
        return self;
      }
      iterator& operator--() {
        --this->m_i;
        return *this;
      }
      iterator operator--(int) {
        const auto self = *this;
        --*this;
        return self;
      }
      iterator& operator+=(const difference_type n) {
        this->m_i += n;
        return *this;
      }
      iterator& operator-=(const difference_type n) {
        this->m_i -= n;
        return *this;
      }
      friend iterator operator+(const iterator& self, const difference_type n) {
        return iterator(self) += n;
      }
      friend iterator operator+(const difference_type n, const iterator& self) {
        return iterator(self) += n;
      }
      friend iterator operator-(const iterator& self, const difference_type n) {
        return iterator(self) -= n;
      }
      friend difference_type operator-(const iterator& lhs, const iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return static_cast<difference_type>(lhs.m_i) - static_cast<difference_type>(rhs.m_i);
      }
      reference operator[](const difference_type n) const {
        return *(*this + n);
      }

      friend bool operator==(const iterator& lhs, const iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i == rhs.m_i;
      }
      friend bool operator!=(const iterator& lhs, const iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i != rhs.m_i;
      }
      friend bool operator<(const iterator& lhs, const iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i < rhs.m_i;
      }
      friend bool operator<=(const iterator& lhs, const iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i <= rhs.m_i;
      }
      friend bool operator>(const iterator& lhs, const iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i > rhs.m_i;
      }
      friend bool operator>=(const iterator& lhs, const iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i >= rhs.m_i;
      }
    };
    class const_iterator {
      const V *m_parent;
      size_type m_i;

    public:
      using difference_type = std::ptrdiff_t;
      using value_type = T;
      using reference = const T&;
      using pointer = const T*;
      using iterator_category = std::random_access_iterator_tag;

      const_iterator() = default;
      const_iterator(const V * const parent, const size_type i) : m_parent(parent), m_i(i) {}

      reference operator*() const {
        return (*this->m_parent)[this->m_i];
      }
      pointer operator->() const {
        return &(*(*this));
      }

      const_iterator& operator++() {
        ++this->m_i;
        return *this;
      }
      const_iterator operator++(int) {
        const auto self = *this;
        ++*this;
        return self;
      }
      const_iterator& operator--() {
        --this->m_i;
        return *this;
      }
      const_iterator operator--(int) {
        const auto self = *this;
        --*this;
        return self;
      }
      const_iterator& operator+=(const difference_type n) {
        this->m_i += n;
        return *this;
      }
      const_iterator& operator-=(const difference_type n) {
        this->m_i -= n;
        return *this;
      }
      friend const_iterator operator+(const const_iterator& self, const difference_type n) {
        return const_iterator(self) += n;
      }
      friend const_iterator operator+(const difference_type n, const const_iterator& self) {
        return const_iterator(self) += n;
      }
      friend const_iterator operator-(const const_iterator& self, const difference_type n) {
        return const_iterator(self) -= n;
      }
      friend difference_type operator-(const const_iterator& lhs, const const_iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return static_cast<difference_type>(lhs.m_i) - static_cast<difference_type>(rhs.m_i);
      }
      reference operator[](const difference_type n) const {
        return *(*this + n);
      }

      friend bool operator==(const const_iterator& lhs, const const_iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i == rhs.m_i;
      }
      friend bool operator!=(const const_iterator& lhs, const const_iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i != rhs.m_i;
      }
      friend bool operator<(const const_iterator& lhs, const const_iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i < rhs.m_i;
      }
      friend bool operator<=(const const_iterator& lhs, const const_iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i <= rhs.m_i;
      }
      friend bool operator>(const const_iterator& lhs, const const_iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i > rhs.m_i;
      }
      friend bool operator>=(const const_iterator& lhs, const const_iterator& rhs) {
        assert(lhs.m_parent == rhs.m_parent);
        return lhs.m_i >= rhs.m_i;
      }
    };
    using reverse_iterator = std::reverse_iterator<iterator>;
    using const_reverse_iterator = std::reverse_iterator<const_iterator>;

    vector() = default;
    explicit vector(size_type n) requires (variable_sized) : Base(n) {}
    vector(size_type n, const_reference value) requires (variable_sized) : Base(n, value) {}
    template <std::input_iterator InputIter>
    vector(const InputIter first, const InputIter last) requires (variable_sized) : Base(first, last) {}
    vector(const T& x, const T& y) requires (N == 2) : Base(x, y) {}
    vector(const T& x, const T& y, const T& z) requires (N == 3) : Base(x, y, z) {}
    vector(const T& x, const T& y, const T& z, const T& w) requires (N == 4) : Base(x, y, z, w) {}
    vector(const std::initializer_list<T> il) : Base(il) {}

    iterator begin() noexcept { return iterator(this, 0); }
    const_iterator begin() const noexcept { return const_iterator(this, 0); }
    const_iterator cbegin() const noexcept { return const_iterator(this, 0); }
    iterator end() noexcept { return iterator(this, this->size()); }
    const_iterator end() const noexcept { return const_iterator(this, this->size()); }
    const_iterator cend() const noexcept { return const_iterator(this, this->size()); }
    reverse_iterator rbegin() noexcept { return std::make_reverse_iterator(this->end()); }
    const_reverse_iterator rbegin() const noexcept { return std::make_reverse_iterator(this->end()); }
    const_reverse_iterator crbegin() const noexcept { return std::make_reverse_iterator(this->cend()); }
    reverse_iterator rend() noexcept { return std::make_reverse_iterator(this->begin()); }
    const_reverse_iterator rend() const noexcept { return std::make_reverse_iterator(this->begin()); }
    const_reverse_iterator crend() const noexcept { return std::make_reverse_iterator(this->cbegin()); }

    size_type size() const noexcept {
      if constexpr (variable_sized) {
        return this->m_values.size();
      } else {
        return N;
      }
    }
    bool empty() const noexcept {
      if constexpr (variable_sized) {
        return this->m_values.empty();
      } else {
        return N == 0;
      }
    }

    auto operator[](this auto&& self, const size_type n) -> std::conditional_t<std::is_const_v<std::remove_reference_t<decltype(self)>>, const_reference, reference> {
      assert(n < self.size());
      if constexpr (has_aliases) {
        if constexpr (N == 2) {
          switch (n) {
            case 0: return self.x;
            default: return self.y;
          }
        } else if constexpr (N == 3) {
          switch (n) {
            case 0: return self.x;
            case 1: return self.y;
            default: return self.z;
          }
        } else {
          switch (n) {
            case 0: return self.x;
            case 1: return self.y;
            case 2: return self.z;
            default: return self.w;
          }
        }
      } else {
        return self.m_values[n];
      }
    }
    reference front() { return *this->begin(); }
    const_reference front() const { return *this->begin(); }
    reference back() { return *this->rbegin(); }
    const_reference back() const { return *this->rbegin(); }

    V operator+() const {
      return *this;
    }
    V operator-() const {
      V res = *this;
      for (auto& v : res) v = -v;
      return res;
    }
    V& operator+=(const V& other) {
      assert(this->size() == other.size());
      for (std::size_t i = 0; i < this->size(); ++i) {
        (*this)[i] += other[i];
      }
      return *this;
    }
    friend V operator+(const V& lhs, const V& rhs) {
      return V(lhs) += rhs;
    }
    V& operator-=(const V& other) {
      assert(this->size() == other.size());
      for (std::size_t i = 0; i < this->size(); ++i) {
        (*this)[i] -= other[i];
      }
      return *this;
    }
    friend V operator-(const V& lhs, const V& rhs) {
      return V(lhs) -= rhs;
    }
    V& operator*=(const T& c) {
      for (auto& v : *this) v *= c;
      return *this;
    }
    friend V operator*(const T& lhs, const V& rhs) {
      return V(rhs) *= lhs;
    }
    friend V operator*(const V& lhs, const T& rhs) {
      return V(lhs) *= rhs;
    }
    V& operator/=(const T& c) {
      for (auto& v : *this) v /= c;
      return *this;
    }
    friend V operator/(const V& lhs, const T& rhs) {
      return V(lhs) /= rhs;
    }

    friend bool operator==(const V& lhs, const V& rhs) {
      return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
    }
    friend bool operator!=(const V& lhs, const V& rhs) {
      return !(lhs == rhs);
    }

    T inner_product(const V& other) const {
      assert(this->size() == other.size());
      T res{};
      for (std::size_t i = 0; i < this->size(); ++i) {
        res += (*this)[i] * other[i];
      }
      return res;
    }
    T l1_norm() const {
      T res{};
      for (const auto& v : *this) {
        res += tools::abs(v);
      }
      return res;
    }
    T squared_l2_norm() const {
      return this->inner_product(*this);
    }
    F l2_norm() const {
      return std::sqrt(static_cast<F>(this->squared_l2_norm()));
    }
    V normalized() const requires std::floating_point<T> {
      return *this / this->l2_norm();
    }

    friend std::ostream& operator<<(std::ostream& os, const V& self) {
      os << '(';
      std::string delimiter = "";
      for (const auto& v : self) {
        os << delimiter << v;
        delimiter = ", ";
      }
      return os << ')';
    }
    friend std::istream& operator>>(std::istream& is, V& self) {
      for (auto& v : self) {
        is >> v;
      }
      return is;
    }

    T outer_product(const V& other) const requires (N == 2) {
      return this->x * other.y - this->y * other.x;
    }
    V turned90() const requires (N == 2) {
      return V{-this->y, this->x};
    }
    V turned270() const requires (N == 2) {
      return V{this->y, -this->x};
    }

    static const std::array<V, 4>& four_directions() requires (N == 2) {
      static const std::array<V, 4> res = {
        V{T(1), T(0)},
        V{T(0), T(1)},
        V{T(-1), T(0)},
        V{T(0), T(-1)}
      };
      return res;
    }
    static const std::array<V, 8>& eight_directions() requires (N == 2) {
      static const std::array<V, 8> res = {
        V{T(1), T(0)},
        V{T(1), T(1)},
        V{T(0), T(1)},
        V{T(-1), T(1)},
        V{T(-1), T(0)},
        V{T(-1), T(-1)},
        V{T(0), T(-1)},
        V{T(1), T(-1)}
      };
      return res;
    }

    V outer_product(const V& other) const requires (N == 3) {
      return V{this->y * other.z - this->z * other.y, this->z * other.x - this->x * other.z, this->x * other.y - this->y * other.x};
    }
    std::array<V, 3> orthonormal_basis() const requires (N == 3 && std::floating_point<T>) {
      assert((*this != V{0, 0, 0}));

      std::array<V, 3> v;
      v[0] = *this;
      v[1] = V{0, this->z, -this->y};
      if (v[1] == V{0, 0, 0}) {
        v[1] = V{-this->z, 0, this->x};
      }
      v[1] -= v[0].inner_product(v[1]) / v[0].inner_product(v[0]) * v[0];

      v[0] = v[0].normalized();
      v[1] = v[1].normalized();
      v[2] = v[0].outer_product(v[1]);

      return v;
    }
  };
}

namespace std {
  template <typename T>
  struct hash<tools::vector<T, 2>> {
    using result_type = std::size_t;
    using argument_type = tools::vector<T, 2>;
    result_type operator()(const argument_type& key) const {
      static const tools::tuple_hash<T, T> hasher;
      return hasher(std::make_tuple(key.x, key.y));
    }
  };
  template <typename T>
  struct hash<tools::vector<T, 3>> {
    using result_type = std::size_t;
    using argument_type = tools::vector<T, 3>;
    result_type operator()(const argument_type& key) const {
      static const tools::tuple_hash<T, T, T> hasher;
      return hasher(std::make_tuple(key.x, key.y, key.z));
    }
  };
  template <typename T>
  struct hash<tools::vector<T, 4>> {
    using result_type = std::size_t;
    using argument_type = tools::vector<T, 4>;
    result_type operator()(const argument_type& key) const {
      static const tools::tuple_hash<T, T, T, T> hasher;
      return hasher(std::make_tuple(key.x, key.y, key.z, key.w));
    }
  };
}


#line 24 "tools/matrix.hpp"

namespace tools {
  namespace detail {
    namespace matrix {
      template <typename X, std::size_t N, std::size_t M>
      class members {
        using R = std::conditional_t<tools::semiring<X>, X, tools::rings::of<tools::groups::plus<X>, tools::multiplicative_structure<X>>>;
        using Add = typename R::add;
        using Mul = typename R::mul;
        using T = typename Add::T;

      protected:
        constexpr static bool variable_sized = false;
        std::array<T, N * M> m_values;
        members() {
          std::ranges::fill(this->m_values, Add::e());
        }
      };
      template <typename X>
      class members<X, std::numeric_limits<std::size_t>::max(), std::numeric_limits<std::size_t>::max()> {
        using R = std::conditional_t<tools::semiring<X>, X, tools::rings::of<tools::groups::plus<X>, tools::multiplicative_structure<X>>>;
        using Add = typename R::add;
        using Mul = typename R::mul;
        using T = typename Add::T;

      protected:
        constexpr static bool variable_sized = true;
        std::vector<T> m_values;
        int m_rows;
        int m_cols;
        members() = default;
        members(const int rows, const int cols) : m_values(rows * cols, Add::e()), m_rows(rows), m_cols(cols) {
          assert(rows >= 0);
          assert(cols >= 0);
        }
        members(const int rows, const int cols, const T& value) : m_values(rows * cols, value), m_rows(rows), m_cols(cols) {
          assert(rows >= 0);
          assert(cols >= 0);
        }
      };
    }
  }

  template <typename X, std::size_t N = std::numeric_limits<std::size_t>::max(), std::size_t M = std::numeric_limits<std::size_t>::max()>
  class matrix : tools::detail::matrix::members<X, N, M> {
    template <typename, std::size_t, std::size_t>
    friend class tools::matrix;
    using Mat = tools::matrix<X, N, M>;
    using Base = tools::detail::matrix::members<X, N, M>;
    constexpr static bool variable_sized = Base::variable_sized;

    using R = std::conditional_t<tools::semiring<X>, X, tools::rings::of<tools::groups::plus<X>, tools::multiplicative_structure<X>>>;
    using Add = typename R::add;
    using Mul = typename R::mul;
    using T = typename Add::T;

  public:
    matrix() = default;
    matrix(const int rows, const int cols) requires variable_sized : Base(rows, cols) {}
    matrix(const int rows, const int cols, const T& value) requires variable_sized : Base(rows, cols, value) {}
    matrix(const std::initializer_list<std::initializer_list<T>> il) requires (!variable_sized) {
      assert(il.size() == this->rows());
      assert(std::ranges::all_of(il, [&](const auto& row) { return std::ssize(row) == this->cols(); }));
      for (int r = 0; r < this->rows(); ++r) {
        std::ranges::copy(il.begin()[r], (*this)[r]);
      }
    }
    matrix(const std::initializer_list<std::initializer_list<T>> il) requires variable_sized : Base(il.size(), il.size() ? il.begin()->size() : 0) {
      assert(std::ranges::all_of(il, [&](const auto& row) { return std::ssize(row) == this->cols(); }));
      for (int r = 0; r < this->rows(); ++r) {
        std::ranges::copy(il.begin()[r], (*this)[r]);
      }
    }
    auto operator[](const int r) {
      assert(0 <= r && r < this->rows());
      return this->m_values.begin() + r * this->cols();
    }
    auto operator[](const int r) const {
      assert(0 <= r && r < this->rows());
      return this->m_values.begin() + r * this->cols();
    }

    int rows() const {
      if constexpr (variable_sized) {
        return this->m_rows;
      } else {
        return N;
      }
    }
    int cols() const {
      if constexpr (variable_sized) {
        return this->m_cols;
      } else {
        return M;
      }
    }

    Mat operator+(this auto&& self) {
      return std::forward<decltype(self)>(self);
    }
    Mat operator-(this auto&& self) requires tools::ring<R> {
      return Mat(std::forward<decltype(self)>(self)) *= Add::inv(Mul::e());
    }
    Mat operator+(this auto&& lhs, const Mat& rhs) {
      return Mat(std::forward<decltype(lhs)>(lhs)) += rhs;
    }
    Mat operator-(this auto&& lhs, const Mat& rhs) requires tools::ring<R> {
      return Mat(std::forward<decltype(lhs)>(lhs)) -= rhs;
    }
    template <std::size_t K> requires (!Mat::variable_sized || K == std::numeric_limits<std::size_t>::max())
    friend tools::matrix<X, N, K> operator*(const Mat& lhs, const tools::matrix<X, M, K>& rhs) {
      assert(lhs.cols() == rhs.rows());
      auto result = [&]() {
        if constexpr (Mat::variable_sized) {
          return tools::matrix<X>(lhs.rows(), rhs.cols());
        } else {
          return tools::matrix<X, N, K>{};
        }
      }();
      for (int i = 0; i < lhs.rows(); ++i) {
        for (int k = 0; k < lhs.cols(); ++k) {
          for (int j = 0; j < rhs.cols(); ++j) {
            result[i][j] = Add::op(result[i][j], Mul::op(lhs[i][k], rhs[k][j]));
          }
        }
      }
      return result;
    }
    friend tools::vector<T, N> operator*(const Mat& lhs, const tools::vector<T, M>& rhs) {
      assert(lhs.cols() == rhs.size());
      auto result = [&]() {
        if constexpr (Mat::variable_sized) {
          return tools::vector<T>(lhs.rows());
        } else {
          return tools::vector<T, N>{};
        }
      }();
      for (int i = 0; i < lhs.rows(); ++i) {
        for (int j = 0; j < lhs.cols(); ++j) {
          result[i] = Add::op(result[i], Mul::op(lhs[i][j], rhs[j]));
        }
      }
      return result;
    }
    Mat operator*(this auto&& lhs, const T& rhs) {
      return Mat(std::forward<decltype(lhs)>(lhs)) *= rhs;
    }
    friend Mat operator/(const Mat& lhs, const tools::matrix<X, M, M>& rhs) requires tools::field<R> {
      const auto inv = rhs.inv();
      assert(inv);
      return lhs * *inv;
    }
    Mat operator/(this auto&& lhs, const T& rhs) requires tools::field<R> {
      return Mat(std::forward<decltype(lhs)>(lhs)) /= rhs;
    }
    auto operator+=(this tools::mutable_type auto&& self, const Mat& other) -> decltype(self) {
      assert(self.rows() == other.rows());
      assert(self.cols() == other.cols());
      for (std::size_t i = 0; i < self.m_values.size(); ++i) {
        self.m_values[i] = Add::op(self.m_values[i], other.m_values[i]);
      }
      return std::forward<decltype(self)>(self);
    }
    auto operator-=(this tools::mutable_type auto&& self, const Mat& other) -> decltype(self) requires tools::ring<R> {
      assert(self.rows() == other.rows());
      assert(self.cols() == other.cols());
      for (std::size_t i = 0; i < self.m_values.size(); ++i) {
        self.m_values[i] = Add::op(self.m_values[i], Add::inv(other.m_values[i]));
      }
      return std::forward<decltype(self)>(self);
    }
    auto operator*=(this tools::mutable_type auto&& self, const tools::matrix<X, M, M>& other) -> decltype(self) {
      self = self * other;
      return std::forward<decltype(self)>(self);
    }
    auto operator*=(this tools::mutable_type auto&& self, const T& c) -> decltype(self) {
      for (auto& v : self.m_values) v = Mul::op(v, c);
      return std::forward<decltype(self)>(self);
    }
    auto operator/=(this tools::mutable_type auto&& self, const tools::matrix<T, M, M>& other) -> decltype(self) requires tools::field<R> {
      self = self / other;
      return std::forward<decltype(self)>(self);
    }
    auto operator/=(this tools::mutable_type auto&& self, const T& c) -> decltype(self) requires tools::field<R> {
      self *= Mul::inv(c);
      return std::forward<decltype(self)>(self);
    }
    friend bool operator==(const Mat& lhs, const Mat& rhs) {
      if constexpr (variable_sized) {
        if (lhs.rows() != rhs.rows()) return false;
        if (lhs.cols() != rhs.cols()) return false;
      }
      return lhs.m_values == rhs.m_values;
    }
    friend bool operator!=(const Mat& lhs, const Mat& rhs) {
      return !(lhs == rhs);
    }

    friend std::istream& operator>>(std::istream& is, Mat& self) {
      for (auto& v : self.m_values) is >> v;
      return is;
    }
    friend std::ostream& operator<<(std::ostream& os, const Mat& self) {
      for (int r = 0; r < self.rows(); ++r) {
        os << '[';
        std::string delimiter = "";
        for (int c = 0; c < self.cols(); ++c) {
          os << delimiter << self[r][c];
          delimiter = ", ";
        }
        os << ']' << '\n';
      }
      return os;
    }

  private:
    std::pair<int, T> internal_gauss_jordan() requires tools::field<R> {
      int rank = 0;
      auto coeff = Mul::e();

      for (int c = 0; c < this->cols(); ++c) {
        int pivot;
        for (pivot = rank; pivot < this->rows() && (*this)[pivot][c] == Add::e(); ++pivot);
        if (pivot == this->rows()) continue;

        if (pivot != rank) {
          for (int cc = c; cc < this->cols(); ++cc) {
            std::swap((*this)[rank][cc], (*this)[pivot][cc]);
          }
          coeff = Mul::op(coeff, Add::inv(Mul::e()));
        }

        {
          const auto scale_inv = Mul::inv((*this)[rank][c]);
          for (int cc = c; cc < this->cols(); ++cc) {
            (*this)[rank][cc] = Mul::op((*this)[rank][cc], scale_inv);
          }
          coeff = Mul::op(coeff, scale_inv);
        }

        for (int r = 0; r < this->rows(); ++r) {
          if (r == rank) continue;
          const auto scale = (*this)[r][c];
          if (scale == Add::e()) continue;
          for (int cc = c; cc < this->cols(); ++cc) {
            (*this)[r][cc] = Add::op((*this)[r][cc], Add::inv(Mul::op((*this)[rank][cc], scale)));
          }
        }

        ++rank;
      }

      return std::make_pair(rank, coeff);
    }

  public:
    int gauss_jordan() requires tools::field<R> {
      return this->internal_gauss_jordan().first;
    }

    int rank() const requires tools::field<R> {
      return (this->rows() < this->cols() ? this->transposed() : Mat(*this)).gauss_jordan();
    }

    tools::matrix<X> solve(const tools::vector<T, N>& b) const requires tools::field<R> {
      assert(this->rows() == b.size());
      assert(this->cols() >= 1);
      auto Ab = [&]() {
        if constexpr (variable_sized) {
          return Mat(this->rows(), this->cols() + 1);
        } else {
          return tools::matrix<X, N, M + 1>{};
        }
      }();
      for (int r = 0; r < this->rows(); ++r) {
        for (int c = 0; c < this->cols(); ++c) {
          Ab[r][c] = (*this)[r][c];
        }
        Ab[r][this->cols()] = b[r];
      }

      Ab.internal_gauss_jordan();

      std::vector<int> ranks(Ab.cols());
      for (int r = 0, cl = 0, cr = 0; r <= Ab.rows(); ++r, cl = cr) {
        for (; cr < Ab.cols() && (r == Ab.rows() || Ab[r][cr] == Add::e()); ++cr);
        for (int c = cl; c < cr; ++c) {
          ranks[c] = r;
        }
      }

      if (ranks[Ab.cols() - 2] < ranks[Ab.cols() - 1]) {
        return tools::matrix<X>(this->rows(), 0);
      }

      std::vector<tools::vector<T>> answers(this->cols());
      int free = this->cols() - ranks.back() - 1;

      for (int cl = this->cols(), cr = this->cols(); cr > 0; cr = cl) {
        for (; cl > 0 && ranks[cl - 1] == ranks[cr - 1]; --cl);
        for (int c = cr - 1; c > cl; --c) {
          answers[c] = tools::vector<T>(this->cols() - ranks.back() + 1, Add::e());
          answers[c][free] = Mul::e();
          --free;
        }
        if (ranks[cl] > 0) {
          answers[cl] = tools::vector<T>(this->cols() - ranks.back() + 1, Add::e());
          answers[cl][this->cols() - ranks.back()] = Ab[ranks[cl] - 1][Ab.cols() - 1];
          for (int c = cl + 1; c < Ab.cols() - 1; ++c) {
            for (int r = 0; r < std::ssize(answers[cl]); ++r) {
              answers[cl][r] = Add::op(answers[cl][r], Add::inv(Ab[ranks[cl] - 1][c] * answers[c][r]));
            }
          }
        } else {
          answers[cl] = tools::vector<T>(this->cols() - ranks.back() + 1, Add::e());
          answers[cl][free] = Mul::e();
          --free;
        }
      }

      tools::matrix<X> answer(this->cols(), this->cols() - ranks.back() + 1);
      for (int r = 0; r < this->cols(); ++r) {
        for (int c = 0; c < this->cols() - ranks.back() + 1; ++c) {
          answer[r][c] = answers[r][c];
        }
      }

      return answer;
    }

    T determinant() const requires tools::field<R> {
      assert(this->rows() == this->cols());

      auto A = *this;
      const auto [rank, coeff] = A.internal_gauss_jordan();

      return rank == A.rows() ? Mul::inv(coeff) : Add::e();
    }

    static Mat e() requires (!variable_sized && N == M) {
      Mat result{};
      for (int i = 0; i < N; ++i) {
        result[i][i] = Mul::e();
      }
      return result;
    }
    static Mat e(const int n) requires variable_sized {
      assert(n >= 0);
      Mat result(n, n, Add::e());
      for (int i = 0; i < n; ++i) {
        result[i][i] = Mul::e();
      }
      return result;
    }

    std::optional<Mat> inv() const requires (variable_sized || N == M) && tools::field<R> {
      assert(this->rows() == this->cols());

      auto AI = [&]() {
        if constexpr (variable_sized) {
          return Mat(this->rows(), this->cols() * 2);
        } else {
          return tools::matrix<X, N, M * 2>{};
        }
      }();
      for (int r = 0; r < this->rows(); ++r) {
        for (int c = 0; c < this->cols(); ++c) {
          AI[r][c] = (*this)[r][c];
        }
        for (int c = this->cols(); c < AI.cols(); ++c) {
          AI[r][c] = Add::e();
        }
        AI[r][this->cols() + r] = Mul::e();
      }

      AI.internal_gauss_jordan();
      for (int i = 0; i < this->rows(); ++i) {
        if (AI[i][i] != Mul::e()) return std::nullopt;
      }

      auto B = [&]() {
        if constexpr (variable_sized) {
          return Mat(this->rows(), this->cols());
        } else {
          return Mat{};
        }
      }();
      for (int r = 0; r < this->rows(); ++r) {
        for (int c = 0; c < this->cols(); ++c) {
          B[r][c] = AI[r][this->cols() + c];
        }
      }
      return B;
    }

    tools::matrix<X, M, N> transposed() const {
      auto A_T = [&]() {
        if constexpr (variable_sized) {
          return Mat(this->cols(), this->rows());
        } else {
          return tools::matrix<X, M, N>{};
        }
      }();
      for (int r = 0; r < this->rows(); ++r) {
        for (int c = 0; c < this->cols(); ++c) {
          A_T[c][r] = (*this)[r][c];
        }
      }
      return A_T;
    }
  };
}


#line 1 "tools/pow.hpp"



#line 1 "tools/square.hpp"



#line 5 "tools/square.hpp"

namespace tools {

  template <tools::monoid M>
  constexpr typename M::T square(const typename M::T& x) noexcept(noexcept(M::op(x, x))) {
    return M::op(x, x);
  }

  template <typename T>
  requires (!tools::monoid<T>)
  constexpr T square(const T& x) noexcept(noexcept(x * x)) {
    return x * x;
  }
}


#line 14 "tools/pow.hpp"

namespace tools {
  namespace detail::pow {
    template <typename X, typename E>
    struct impl {
      template <typename G = X>
      requires std::same_as<G, X> && tools::group<G>
      constexpr typename G::T operator()(const typename G::T& b, const E n) const
      noexcept(noexcept(G::e()) && noexcept(G::op(b, b)) && noexcept(G::inv(b)))
      requires tools::integral<E> {
        if (n < 0) return G::inv((*this)(b, -n));
        if (n == 0) return G::e();
        if (n % 2 == 0) return tools::square<G>((*this)(b, n / 2));
        return G::op((*this)(b, n - 1), b);
      }

      template <typename M = X>
      requires (std::same_as<M, X> && !tools::group<M> && tools::monoid<M>)
      constexpr typename M::T operator()(const typename M::T& b, const E n) const
      noexcept(noexcept(M::e()) && noexcept(M::op(b, b)))
      requires tools::integral<E> {
        assert(n >= 0);
        if (n == 0) return M::e();
        if (n % 2 == 0) return tools::square<M>((*this)(b, n / 2));
        return M::op((*this)(b, n - 1), b);
      }

      constexpr X operator()(const X& b, const E n) const
      noexcept(noexcept(impl<tools::multiplicative_structure<X>, E>{}(b, n)))
      requires (!tools::monoid<X> && tools::integral<E>) {
        return impl<tools::multiplicative_structure<X>, E>{}(b, n);
      }

      constexpr decltype(auto) operator()(const X& b, const E n) const
      noexcept(noexcept(std::pow(b, n)))
      requires (!tools::monoid<X> && !tools::integral<E>) {
        return std::pow(b, n);
      }
    };
  }

  template <typename X = void>
  constexpr decltype(auto) pow(auto&& b, auto&& n) noexcept(noexcept(tools::detail::pow::impl<std::conditional_t<std::same_as<X, void>, std::remove_cvref_t<decltype(b)>, X>, std::remove_cvref_t<decltype(n)>>{}(std::forward<decltype(b)>(b), std::forward<decltype(n)>(n)))) {
    return tools::detail::pow::impl<std::conditional_t<std::same_as<X, void>, std::remove_cvref_t<decltype(b)>, X>, std::remove_cvref_t<decltype(n)>>{}(std::forward<decltype(b)>(b), std::forward<decltype(n)>(n));
  }
}


#line 13 "tests/matrix/ring.test.cpp"

using u32 = std::uint32_t;

struct monoid {
  static inline int N;
  using T = tools::matrix<tools::rings::xor_and<u32>>;
  static T op(const T& a, const T& b) {
    return a * b;
  }
  static T e() {
    return T::e(N);
  }
};

u32 solve(const int K, const int M, const std::vector<u32>& A, const std::vector<u32>& C) {
  monoid::N = K;
  tools::matrix<tools::rings::xor_and<u32>> matrix(K, K);
  for (int i = 0; i + 1 < K; ++i) {
    matrix[i][i + 1] = tools::monoids::bit_and<u32>::e();
  }
  for (int j = 0; j < K; ++j) {
    matrix[K - 1][j] = C[K - 1 - j];
  }
  tools::vector<u32> vector(K);
  for (int i = 0; i < K; ++i) {
    vector[i] = A[i];
  }
  return (tools::pow<monoid>(matrix, M - 1) * vector)[0];
}

void sample_01() {
  const int K = 3;
  const int M = 5;
  const std::vector<u32> A = {10, 20, 30};
  const std::vector<u32> C = {7, 19, 13};
  assert_that(solve(K, M, A, C) == 16);
}

void sample_02() {
  const int K = 5;
  const int M = 100;
  const std::vector<u32> A = {2345678901, 1001001001, 3333333333, 3141592653, 1234567890};
  const std::vector<u32> C = {2147483648, 2147483647, 4294967295, 4294967294, 3434343434};
  assert_that(solve(K, M, A, C) == 1067078691);
}

void sample_03() {
  const int K = 30;
  const int M = 999999999;
  const std::vector<u32> A = {11627, 5078, 8394, 6412, 10346, 3086, 3933, 668, 9879, 11739, 4501, 6108, 12336, 8771, 2768, 2438, 2153, 7047, 5476, 313, 1264, 369, 12070, 10743, 10663, 747, 370, 4671, 5235, 3439};
  const std::vector<u32> C = {114, 3613, 3271, 5032, 11241, 6961, 3628, 150, 12191, 2396, 7638, 3046, 11594, 8162, 11136, 786, 9878, 2356, 11660, 1070, 3649, 10882, 9746, 1415, 3307, 7077, 9319, 9981, 3437, 544};
  assert_that(solve(K, M, A, C) == 2148);
}

int main() {
  std::cin.tie(nullptr);
  std::ios_base::sync_with_stdio(false);

  sample_01();
  sample_02();
  sample_03();

  return 0;
}
Back to top page