Tifa's CP Library

:heavy_check_mark: test/cpv_local/edh/hamming.cpp

Depends on

Code

// competitive-verifier: STANDALONE

#include "../../../src/edh/hamming/lib.hpp"
#include "../../../src/util/rand/lib.hpp"
#include "../base.hpp"

using namespace tifa_libs;
rand_gen<dbitset::word_t> g;

void test(u64 n) {
  dbitset s(n, g);

  timer_(auto v = hamming::encode(s));
  auto m = v.size() - n - 1;
  check_bool(v.size() <= (1_u64 << m), check_param(n), check_param(m), check_param(s.to_string()), check_param(v.to_string()));

  timer_(auto t1 = hamming::decode<false>(v));
  check(t1.to_string(), s.to_string(), check_param(v.to_string()));

  if (v.size() > 1) {
    auto v2 = v;
    rand_gen<u64> g2(1, v.size() - 1);
    auto pos = g2();
    v2.flip(pos);

    timer_(auto t2 = hamming::decode<true>(v2));
    check(v2.to_string(), v.to_string(), check_param(pos));
    check_bool(t2.has_value(), check_param(pos), check_param(s.to_string()), check_param(v.to_string()));
    check(t2->to_string(), s.to_string(), check_param(pos), check_param(v.to_string()));
  }
}

int main() {
  flt_ (u32, i, 0, 20) {
    timer_(test(i));
  }
  flt_ (u32, i, 2, 10) {
    timer_(test((1 << i) - (i + 1)));
  }
  timer_(test(1000));
  timer_(test(10000));
  timer_(test(200000));
  timer_(test(500000));
  timer_(test(100000));
  timer_(test(200000));
  timer_(test(500000));
  timer_(test(1000000));
  timer_(test(2000000));
  timer_(test(5000000));
}
#line 1 "test/cpv_local/edh/hamming.cpp"
// competitive-verifier: STANDALONE

#line 2 "src/edh/hamming/lib.hpp"

#line 2 "src/ds/dbitset/lib.hpp"

#line 2 "src/bit/parity/lib.hpp"

#line 2 "src/util/util/lib.hpp"
// https://github.com/Tiphereth-A/CP-lib
#include <bits/extc++.h>
// clang-format off
namespace tifa_libs {

#define CEXP constexpr
#define CEXPE constexpr explicit
#define CR const&
#define CP const*
#define PC *const
#define CPC const*const
#define TPN typename
#define NE noexcept
#define CNE const noexcept
#define ND [[nodiscard]]
#define cT_(...) std::conditional_t<sizeof(__VA_ARGS__) <= sizeof(size_t) * 2, __VA_ARGS__, __VA_ARGS__ CR>
// NOLINTNEXTLINE(misc-const-correctness)
#define flt_(T, i, l, r, ...) for (T i = (l), i##e = (r)__VA_OPT__(, ) __VA_ARGS__; i < i##e; ++i)
#define retif_(cond, if_true, ...) if cond return if_true __VA_OPT__(; else return __VA_ARGS__)
#ifdef ONLINE_JUDGE
#undef assert
#define assert(x) 42
#endif

using namespace std::ranges;
using namespace std::literals;

template <class T>
CEXP T abs(T x) NE { retif_((x < 0), -x, x); }

}  // namespace tifa_libs
// clang-format on
#line 4 "src/bit/parity/lib.hpp"

namespace tifa_libs {

template <class T>
CEXP int parity(T x) NE {
  CEXP int nd = sizeof(T) * 8;
  static_assert(nd <= 128);
  CEXP int nd_ull = sizeof(unsigned long long) * 8;
  if CEXP (nd <= sizeof(unsigned) * 8) return __builtin_parity(x);
  else if CEXP (nd <= sizeof(unsigned long) * 8) return __builtin_parityl(x);
  else if CEXP (nd <= nd_ull) return __builtin_parityll(x);
  else return __builtin_parityll(x >> nd_ull) ^ __builtin_parityll(x & (unsigned long long)(-1));
}

}  // namespace tifa_libs
#line 2 "src/util/traits/math/lib.hpp"
// clang-format off
#line 2 "src/util/alias/num/lib.hpp"

#line 4 "src/util/alias/num/lib.hpp"
// clang-format off
namespace tifa_libs {

#define mk0_(w, t) using w = t; using c##w = const t
#define mk_(w, t) mk0_(w, t); CEXP w operator""_##w(unsigned long long x) NE { return (w)x; }
mk_(i8, int8_t) mk_(u8, uint8_t) mk_(i16, int16_t) mk_(u16, uint16_t) mk_(i32, int32_t) mk_(u32, uint32_t) mk_(i64, int64_t) mk_(u64, uint64_t) mk_(isz, ssize_t) mk_(usz, size_t) mk_(chr, char) mk_(schr, signed char) mk_(uchr, unsigned char) mk_(sint, signed) mk_(uint, unsigned);
mk0_(i128, __int128_t); mk0_(u128, __uint128_t); mk0_(f32, float); mk0_(f64, double); mk0_(f128, long double);
#undef mk0_
#undef mk_

}  // namespace tifa_libs
// clang-format on
#line 4 "src/util/traits/math/lib.hpp"

namespace tifa_libs {

template <class T> concept char_c = std::same_as<T, char> || std::same_as<T, signed char> || std::same_as<T, unsigned char>;
#pragma GCC diagnostic ignored "-Wpedantic"
template <class T> concept s128_c = std::same_as<T, __int128_t> || std::same_as<T, __int128>;
template <class T> concept u128_c = std::same_as<T, __uint128_t> || std::same_as<T, unsigned __int128>;
template <class T> concept i128_c = s128_c<T> || u128_c<T>;
#pragma GCC diagnostic warning "-Wpedantic"
template <class T> concept imost64_c = std::integral<T> && sizeof(T) * __CHAR_BIT__ <= 64;
template <class T> concept smost64_c = imost64_c<T> && std::signed_integral<T>;
template <class T> concept umost64_c = imost64_c<T> && std::unsigned_integral<T>;
template <class T> concept int_c = i128_c<T> || imost64_c<T>;
template <class T> concept sint_c = s128_c<T> || smost64_c<T>;
template <class T> concept uint_c = u128_c<T> || umost64_c<T>;
template <class T> concept arithm_c = std::is_arithmetic_v<T> || int_c<T>;
template <class T> concept mint_c = requires(T x) { {x.mod()} -> uint_c; {x.val()} -> uint_c; };
template <class T> concept dft_c = requires(T x, std::vector<TPN T::data_t> v, u32 n) { {x.size()} -> std::same_as<u32>; x.bzr(n); x.dif(v, n); x.dit(v, n); };
template <class T> concept ntt_c = dft_c<T> && requires(T x) { T::max_size; T::G; };

template <class T> struct to_sint : std::make_signed<T> {};
template <> struct to_sint<u128> { using type = i128; };
template <> struct to_sint<i128> { using type = i128; };
template <class T> using to_sint_t = TPN to_sint<T>::type;
template <class T> struct to_uint : std::make_unsigned<T> {};
template <> struct to_uint<u128> { using type = u128; };
template <> struct to_uint<i128> { using type = u128; };
template <class T> using to_uint_t = TPN to_uint<T>::type;
template <arithm_c T> struct to_bigger : std::make_unsigned<T> {};
#define _(w,ww) template <> struct to_bigger<w> { using type = ww; }
#define _2(w,ww) _(i##w,i##ww); _(u##w,u##ww);
_2(8, 16); _2(16, 32); _2(32, 64); _2(64, 128); _(f32, f64); _(f64, f128);
#undef _2
#undef _
template <class T> using to_bigger_t = TPN to_bigger<T>::type;

template <arithm_c T> CEXP T inf_v = [] {
    if CEXP(sint_c<T>) return T(to_uint_t<T>(-1) / 4 - 1);
    else if CEXP(uint_c<T>) return T(-1) / 2 - 1;
    else return std::numeric_limits<T>::max() / 2 - 1;
}();

}  // namespace tifa_libs
// clang-format on
#line 2 "src/util/traits/others/lib.hpp"
// clang-format off
#line 2 "src/util/alias/others/lib.hpp"

#line 2 "src/util/consts/lib.hpp"

#line 4 "src/util/consts/lib.hpp"
// clang-format off
namespace tifa_libs {
using std::numbers::pi_v;
template <std::floating_point FP>
inline FP eps_v = std::sqrt(std::numeric_limits<FP>::epsilon());
template <std::floating_point FP>
CEXP void set_eps(FP v) NE { eps_v<FP> = v; }
CEXP u32 TIME = ((__TIME__[0] & 15) << 20) | ((__TIME__[1] & 15) << 16) | ((__TIME__[3] & 15) << 12) | ((__TIME__[4] & 15) << 8) | ((__TIME__[6] & 15) << 4) | (__TIME__[7] & 15);
CEXP auto STR2U16 = [] { std::array<u32, 65536> table{}; table.fill(-1_u32); flt_ (u32, i, 48, 58) flt_ (u32, j, 48, 58) table[i << 8 | j] = (j & 15) * 10 + (i & 15); return table; }();

inline const auto fn_0 = [](auto&&...) NE {};
inline const auto fn_is0 = [](auto x) NE { return x == 0; };
}  // namespace tifa_libs
// clang-format on
#line 4 "src/util/alias/others/lib.hpp"

namespace tifa_libs {

template <class T>
struct chash {
  CEXP static u64 C = u64(pi_v<f128> * 2e18) | 71;
  CEXP u64 operator()(T x) CNE { return __builtin_bswap64(((u64)x ^ TIME) * C); }
};
// clang-format off
#define mk_(w, t) using w = t; using c##w = const t;
mk_(strn, std::string) mk_(strnv, std::string_view)
#undef mk_
template <class T> struct edge_t { T w; u32 u, v; CEXP auto operator<=>(edge_t CR) const = default; }; template <class T> using cedge_t = const edge_t<T>;
template <class T> struct pt3 { T _0, _1, _2; CEXP auto operator<=>(pt3 CR) const = default; }; template <class T> using cpt3 = const pt3<T>;
template <class T> struct pt4 { T _0, _1, _2, _3; CEXP auto operator<=>(pt4 CR) const = default; }; template <class T> using cpt4 = const pt4<T>;
#define mkT_(w, t, ...) template <class T> using w = t __VA_OPT__(, ) __VA_ARGS__; template <class T> using c##w = const t __VA_OPT__(, ) __VA_ARGS__;
mkT_(ptt, std::pair<T, T>) mkT_(alc, std::pmr::polymorphic_allocator<T>) mkT_(vec, std::vector<T>) mkT_(vvec, vec<vec<T>>) mkT_(v3ec, vvec<vec<T>>) mkT_(vecpt, vec<ptt<T>>) mkT_(vvecpt, vvec<ptt<T>>) mkT_(ptvec, ptt<vec<T>>) mkT_(ptvvec, ptt<vvec<T>>)
#undef mkT_
template <class T> using itl = std ::initializer_list<T>;
template <class T, usz ext = std::dynamic_extent> using spn = std::span<T const, ext>;
template <class T, usz N> using arr = std::array<T, N>; template <class T, usz N> using carr = std::array<const T, N>;
template <class U, class T> using vecp = vec<std::pair<U, T>>; template <class U, class T> using vvecp = vvec<std::pair<U, T>>;
template <class U, class T> using vvecp = vvec<std::pair<U, T>>; template <class U, class T> using vvvecp = vvec<vvec<std::pair<U, T>>>;
#ifdef PB_DS_ASSOC_CNTNR_HPP
template <class T, class C = std::less<T>> using set = __gnu_pbds::tree<T, __gnu_pbds::null_type, C>;
template <class K, class V, class C = std::less<K>> using map = __gnu_pbds::tree<K, V, C>;
// hset<u64> s({}, {}, {}, {}, {1<<16});
template <class T, class HF = chash<T>> using hset = __gnu_pbds::gp_hash_table<T, __gnu_pbds::null_type, HF>;
// hmap<u64, int> s({}, {}, {}, {}, {1<<16});
template <class K, class V, class HF = chash<K>> using hmap = __gnu_pbds::gp_hash_table<K, V, HF>;
#else
using std::set, std::map;
template <class T, class HF = chash<T>> using hset = std::unordered_set<T, HF>;
template <class K, class V, class HF = chash<K>> using hmap = std::unordered_map<K, V, HF>;
#endif
#ifdef PB_DS_PRIORITY_QUEUE_HPP
template <class T, class C = std::less<T>> using pq = __gnu_pbds::priority_queue<T, C>;
#else
template <class T, class C = std::less<T>> using pq = std::priority_queue<T, vec<T>, C>;
#endif
template <class T> using pqg = pq<T, std::greater<T>>;
// clang-format on
#define mk1_(V, A, T) using V##A = V<T>;
#define mk_(V, A, T) mk1_(V, A, T) mk1_(c##V, A, T)
#define mk(A, T) mk_(edge_t, A, T) mk_(ptt, A, T) mk_(pt3, A, T) mk_(pt4, A, T) mk_(vec, A, T) mk_(vvec, A, T) mk_(v3ec, A, T) mk_(vecpt, A, T) mk_(vvecpt, A, T) mk_(ptvec, A, T) mk_(ptvvec, A, T) mk1_(spn, A, T) mk1_(itl, A, T)
mk(b, bool) mk(c, chr) mk(i, i32) mk(u, u32) mk(ii, i64) mk(uu, u64) mk(t, isz) mk(z, usz) mk(f, f32) mk(d, f64) mk(s, strn);
#undef mk
#undef mk_
#undef mk1_

}  // namespace tifa_libs
#line 4 "src/util/traits/others/lib.hpp"

namespace tifa_libs {

//! only for template without non-type argument
template <class, template <class...> class> CEXP bool specialized_from_v = false;
template <template <class...> class T, class... Args> CEXP bool specialized_from_v<T<Args...>, T> = true;
static_assert(specialized_from_v<vecu, std::vector>);
template <class T> concept container_c = common_range<T> && !std::is_array_v<std::remove_cvref_t<T>> && !std::same_as<std::remove_cvref_t<T>, strn> && !std::same_as<std::remove_cvref_t<T>, strnv>;
template <class T> concept istream_c = std::derived_from<T, std::istream> || std::derived_from<T, std::wistream> || requires(T is) { is.peek(); };
template <class T> concept ostream_c = std::derived_from<T, std::ostream> || std::derived_from<T, std::wostream> || requires(T os) { os.flush(); };

}  // namespace tifa_libs
// clang-format on
#line 6 "src/ds/dbitset/lib.hpp"

namespace tifa_libs {

struct dbitset {
  using word_t = u64;
  static CEXP u32 word_width = 64;

 protected:
  u64 sz;
  vec<word_t> data;

  static CEXP auto idx_word(u64 n) NE { return u32(n / word_width); }
  static CEXP auto idx_bit(u64 n) NE { return (u32)n % word_width; }
  static CEXP auto word_count(u64 n) NE { return idx_word(n) + !!idx_bit(n); }
  static CEXP auto mask_bit(u64 n) NE { return 1_u64 << idx_bit(n); }
  static CEXP u64 mask_outrange(u64 n) NE {
    if (!idx_bit(n)) return 0;
    return -1_u64 << idx_bit(n);
  }

  CEXP void lsh_(umost64_c auto n) NE {
    if (data.empty()) {
      bit_resize(n);
      return;
    }
    if (!n) return;
    const auto pre = data.size();
    cu32 w = idx_word(n), ofs = idx_bit(n);
    data.resize(data.size() + w);
    if (!ofs)
      for (auto i = pre - 1; ~i; --i) data[i + w] = data[i];
    else {
      cu32 cofs = word_width - ofs;
      for (auto i = pre - 1; i; --i) data[i + w] = data[i] << ofs | data[i - 1] >> cofs;
      data[w] = data[0] << ofs;
    }
    fill(begin(data), begin(data) + w, 0), sz += n;
  }
  CEXP void rsh_(umost64_c auto n) NE {
    if (n >= sz) {
      sz = 0, data.clear();
      return;
    }
    if (!n) return;
    cu32 w = idx_word(n), ofs = idx_bit(n);
    cu32 lim = word_size() - w - 1;
    if (!ofs)
      flt_ (u32, i, 0, lim + 1) data[i] = data[i + w];
    else {
      cu32 cofs = word_width - ofs;
      flt_ (u32, i, 0, lim) data[i] = data[i + w] >> ofs | data[i + w + 1] << cofs;
      data[lim] = data.back() >> ofs;
    }
    data.resize(data.size() - w), sz -= n;
  }

 public:
  CEXPE dbitset(usz n, bool val = false) NE { bit_resize(n, val); }
  CEXP dbitset(usz n, int_c auto val) NE { from_integer(val, n); }
  template <class F>
  requires requires(F f) { { f() } -> std::same_as<word_t>; }
  CEXP dbitset(usz n, F&& gen) NE { set(std::forward<F>(gen), n); }
  CEXP dbitset(strnv s, usz pos = 0, usz n = -1_usz, chr zero = '0', chr one = '1') NE { set(s, pos, n, zero, one); }

  CEXP dbitset& from_integer(int_c auto val, usz n = -1_usz) NE {
    const auto nbits = min({n, sizeof(val) * 8});
    if (bit_resize(nbits); val && !data.empty()) {
      if CEXP (sizeof(val) * 8 <= word_width) data[0] = (word_t)val & ~mask_outrange(sz);
      else {
        for (u32 i = 0; i < data.size() && val; val >>= word_width, ++i) data[i] = (word_t)val;
        data.back() &= ~mask_outrange(sz);
      }
    }
    return *this;
  }
  CEXP dbitset& set(strnv s, usz pos = 0, usz n = -1_usz, chr = '0', chr one = '1') NE {
    const auto nbits = min({sz, n, s.size() - pos});
    bit_resize(nbits);
    for (usz i = nbits; i; --i)
      if (s[pos + nbits - i] == one) set(i - 1);
    return *this;
  }
  template <class F>
  requires requires(F f) { { f() } -> std::same_as<word_t>; }
  CEXP dbitset& set(F&& gen, usz n) NE {
    bit_resize(n);
    if (!data.empty())
      for (auto& i : data) i = gen();
    return *this;
  }

  friend CEXP bool operator==(dbitset CR l, dbitset CR r) NE { return l.sz == r.sz && l.data == r.data; }

  ND CEXP u64 find_first() CNE {
    flt_ (u32, i, 0, word_size())
      if (data[i]) return i * 64_u64 + (u32)std::countr_zero(data[i]);
    return sz;
  }
  ND CEXP u64 find_next(u64 prev) CNE {
    if (++prev >= sz) return sz;
    size_t i = idx_word(prev);
    if (const word_t _ = data[i] & -1_u64 << idx_bit(prev); _) return i * word_width + (u32)std::countr_zero(_);
    for (++i; i < word_size(); ++i)
      if (data[i]) return i * word_width + (u32)std::countr_zero(data[i]);
    return sz;
  }

  CEXP auto& raw() NE { return data; }
  ND CEXP word_t CR getword(usz n) CNE { return data[idx_word(n)]; }
  CEXP word_t& getword(usz n) NE { return data[idx_word(n)]; }
  CEXP bool operator[](usz n) CNE { return getword(n) & mask_bit(n); }

  ND CEXP bool all() CNE {
    if (data.empty()) return false;
    flt_ (u32, i, 0, (u32)data.size() - !!idx_bit(sz))
      if (~data[i]) return false;
    if (idx_bit(sz)) return (data.back() & ~mask_outrange(sz)) == ~mask_outrange(sz);
    return true;
  }
  ND CEXP bool any() CNE {
    if (data.empty()) return false;
    for (auto i : data)
      if (i) return true;
    return false;
  }
  ND CEXP bool none() CNE {
    if (data.empty()) return false;
    return !any();
  }
  ND CEXP u64 count() CNE {
    u64 ans = 0;
    for (const auto i : data) ans += (u32)std::popcount(i);
    return ans;
  }
  ND CEXP bool parity() CNE {
    bool ans = false;
    for (const auto i : data) ans ^= ::tifa_libs::parity(i);
    return ans;
  }

  ND CEXP u64 CR size() CNE { return sz; }
  ND CEXP u32 word_size() CNE { return (u32)data.size(); }
  CEXP void bit_resize(usz n, bool val = false) NE {
    data.resize(word_count(sz = n), val ? -1_u64 : 0);
    if (val && !data.empty()) data.back() &= ~mask_outrange(sz);
  }

#define OP__(op)                                              \
  CEXP dbitset& operator op## = (dbitset CR r)NE {            \
    if (r.sz > sz) data.resize(r.word_size()), sz = r.sz;     \
    if (data.empty()) return *this;                           \
    flt_ (u32, i, 0, r.word_size()) data[i] op## = r.data[i]; \
    data.back() &= ~mask_outrange(sz);                        \
    return *this;                                             \
  }                                                           \
  CEXP dbitset operator op(dbitset CR r) CNE { return dbitset(*this) op## = r; }
  OP__(&)
  OP__(|)
  OP__(^)
#undef OP__
  CEXP dbitset operator~() CNE { return dbitset(*this).flip(); }
  CEXP dbitset& operator<<=(imost64_c auto n) NE {
    if (n < 0) [[unlikely]]
      rsh_((to_uint_t<decltype(n)>)-n);
    else lsh_((to_uint_t<decltype(n)>)n);
    return *this;
  }
  CEXP dbitset operator<<(imost64_c auto n) CNE { return dbitset(*this) <<= n; }
  CEXP dbitset& operator>>=(imost64_c auto n) NE {
    if (n < 0) [[unlikely]]
      lsh_((to_uint_t<decltype(n)>)-n);
    else rsh_((to_uint_t<decltype(n)>)n);
    return *this;
  }
  CEXP dbitset operator>>(imost64_c auto n) CNE { return dbitset(*this) >>= n; }

  CEXP dbitset& set() NE {
    fill(data, -1_u64);
    if (!data.empty()) data.back() &= ~mask_outrange(sz);
    return *this;
  }
  CEXP dbitset& set(usz pos, bool val = true) NE {
    if (val) getword(pos) |= mask_bit(pos);
    else return reset(pos);
    return *this;
  }
  CEXP dbitset& reset() NE {
    fill(data, 0);
    return *this;
  }
  CEXP dbitset& reset(usz pos) NE {
    getword(pos) &= ~mask_bit(pos);
    return *this;
  }
  CEXP dbitset& flip() NE {
    for (auto& i : data) i = ~i;
    if (!data.empty()) data.back() &= ~mask_outrange(sz);
    return *this;
  }
  CEXP dbitset& flip(usz pos) NE {
    getword(pos) ^= mask_bit(pos);
    return *this;
  }

  ND CEXP strn to_string(chr zero = '0', chr one = '1') CNE {
    strn ans(sz, zero);
    if (zero != one) [[likely]]
      for (auto n = find_first(); n < sz; n = find_next(n)) ans[sz - n - 1] = one;
    return ans;
  }
  template <int_c T>
  ND CEXP T to_integer() CNE {
    if CEXP (sizeof(T) * 8 <= word_width) {
      retif_((data.empty()) [[unlikely]], (T)0, (T)data[0]);
    } else {
      retif_((data.empty()) [[unlikely]], (T)0);
      retif_((data.size() > 1), (T)data[1] << word_width | (T)data[0], (T)data[0]);
    }
  }
  ND CEXP auto to_u32() CNE { return to_integer<u32>(); }
  ND CEXP auto to_u64() CNE { return to_integer<u64>(); }
  ND CEXP auto to_ulong() CNE { return to_integer<unsigned long>(); }
  ND CEXP auto to_ullong() CNE { return to_integer<unsigned long long>(); }

  friend auto& operator>>(istream_c auto& is, dbitset& b) NE {
    strn s;
    (is >> s), b.set(s);
    return is;
  }
  friend auto& operator<<(ostream_c auto& os, dbitset CR b) NE { return os << b.to_string(); }
};

}  // namespace tifa_libs
#line 4 "src/edh/hamming/lib.hpp"

namespace tifa_libs {

class hamming {
  static CEXP u32 get_m(u64 n) NE {
    u32 m = (u32)std::bit_width(n);
    if ((1_u64 << m) - m - 1 < n) ++m;
    return m;
  }
  static CEXP auto get_nm(u64 len) NE {
    cu32 m = (u32)std::bit_width(len - 1);
    return std::make_pair(len - m - 1, m);
  }

 public:
  static CEXP auto encode(dbitset CR msg) NE {
    cu64 n = msg.size(), m = get_m(n), len = n + m + 1;
    dbitset code(len);
    flt_ (u64, i, 1, len, j = 0)
      if (!std::has_single_bit(i)) code.set(i, msg[j++]);
    u64 _ = 0;
    for (u64 j = code.find_next(0); j < len; j = code.find_next(j)) _ ^= j;
    for (u64 i = 1; i < len; i *= 2)
      if (_ & i) code.flip(i);
    code.set(0, code.parity());
    return code;
  }
  template <bool err_correction = false>  // == true -> auto correction if possible
  static CEXP auto decode(dbitset& code) NE {
    auto const [n, m] = get_nm(code.size());
    std::optional<dbitset> ret;
    if CEXP (err_correction) {
      usz err = 0;
      for (u64 i = code.find_next(0); i < code.size(); i = code.find_next(i)) err ^= i;
      if (err) {
        retif_((!code.parity()), ret);
        code.flip(err);
      }
    }
    dbitset ans(n);
    dbitset::word_t _ = 0;
    u32 wj = 0;
    flt_ (u64, i, 1, code.size(), j = 0) {
      if (std::has_single_bit(i)) continue;
      if (code[i]) _ |= ((dbitset::word_t)1 << j);
      if (++j == dbitset::word_width) ans.raw()[wj++] = _, j = _ = 0;
    }
    if (_) ans.raw()[wj] = _;
    if CEXP (err_correction) {
      ret.emplace(ans);
      return ret;
    } else return ans;
  }
};
}  // namespace tifa_libs
#line 2 "src/util/rand/lib.hpp"

#line 5 "src/util/rand/lib.hpp"

namespace tifa_libs {

template <class T>
requires std::is_arithmetic_v<T>
class rand_gen {
  using res_t = std::conditional_t<sizeof(T) <= 4, u32, u64>;
  using res_wt = std::conditional_t<sizeof(T) <= 4, u64, u128>;
  // clang-format off
  struct mt19937_param { static CEXP u32 w = 32, n = 624, m = 397, r = 31, a = 0x9908b0df, u = 11, d = 0xffffffff, s = 7, b = 0x9d2c5680, t = 15, c = 0xefc60000, l = 18, f = 1812433253; };
  struct mt19937_64_param { static CEXP u64 w = 64, n = 312, m = 156, r = 31, a = 0xb5026f5aa96619e9, u = 29, d = 0x5555555555555555, s = 17, b = 0x71d67fffeda60000, t = 37, c = 0xfff7eee000000000, l = 43, f = 6364136223846793005; };
  using pm = std::conditional_t<std::is_same_v<res_t, u32>, mt19937_param, mt19937_64_param>;
  // clang-format on
  T a_, b_;

  arr<res_t, pm::n> x_;
  u32 p_;
  CEXP void gen_() NE {
    CEXP res_t um = (~res_t()) << pm::r, lm = ~um;
    res_t _;
    flt_ (res_t, i, p_ = 0, pm::n - pm::m) _ = ((x_[i] & um) | (x_[i + 1] & lm)), x_[i] = (x_[i + pm::m] ^ (_ >> 1) ^ ((_ & 1) ? pm::a : 0));
    flt_ (res_t, i, pm::n - pm::m, pm::n - 1) _ = ((x_[i] & um) | (x_[i + 1] & lm)), x_[i] = (x_[i + (pm::m - pm::n)] ^ (_ >> 1) ^ ((_ & 1) ? pm::a : 0));
    _ = ((x_[pm::n - 1] & um) | (x_[0] & lm)), x_[pm::n - 1] = (x_[pm::m - 1] ^ (_ >> 1) ^ ((_ & 1) ? pm::a : 0));
  }

 public:
  CEXPE rand_gen(T a = std::numeric_limits<T>::min(), T b = std::numeric_limits<T>::max(), res_t sd = (res_t)TIME) NE : a_(a), b_(b) { assert(a < b || (std::is_integral_v<T> && a == b)), seed(sd); }

  CEXP void range(T min, T max) NE { assert(min < max || (std::is_integral_v<T> && min == max)), a_ = min, b_ = max; }
  void seed() NE { seed((res_t)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count()); }
  CEXP void seed(res_t sd) NE {
    x_[0] = sd & gen_max();
    flt_ (res_t, i, 1, p_ = pm::n) x_[i] = ((x_[i - 1] ^ (x_[i - 1] >> (pm::w - 2))) * pm::f + i % pm::n) & gen_max();
  }
  ND CEXP res_t gen_min() CNE { return 0; }
  ND CEXP res_t gen_max() CNE {
    if CEXP (sizeof(res_t) * 8 == pm::w) return ~res_t();
    else return ((res_t)1 << pm::w) - 1;
  }
  CEXP res_t next() NE {
    if (p_ >= pm::n) gen_();
    res_t _ = x_[p_++];
    _ ^= (_ >> pm::u) & pm::d, _ ^= (_ << pm::s) & pm::b, _ ^= (_ << pm::t) & pm::c, _ ^= (_ >> pm::l);
    return _;
  }
  CEXP T operator()() NE {
    if CEXP (std::integral<T>) {
      const res_wt r = (res_wt)b_ - (res_wt)a_ + 1;
      res_wt p = r * next();
      if (auto l = (res_t)p, _ = res_t(res_wt(-(res_t)r) % r); l < r)
        while (l < _) l = res_t(p = r * next());
      return T((res_t)(p >> pm::w) + (res_t)a_);
    } else return T(next() / (f128)((u128)gen_max() + 1) * (b_ - a_) + a_);
  }
};

}  // namespace tifa_libs
#line 2 "test/cpv_local/base.hpp"

#line 2 "src/io/container/lib.hpp"

#line 4 "src/io/container/lib.hpp"

namespace tifa_libs {

auto& operator>>(tifa_libs::istream_c auto& is, tifa_libs::container_c auto& x) NE {
  for (auto& i : x) is >> i;
  return is;
}
auto& operator<<(tifa_libs::ostream_c auto& os, tifa_libs::container_c auto CR x) NE {
  if (begin(x) == end(x)) [[unlikely]]
    return os;
  auto it = begin(x);
  for (os << *it++; it != end(x); ++it) os << ' ' << *it;
  return os;
}

}  // namespace tifa_libs
#line 2 "src/io/i128/lib.hpp"

#line 5 "src/io/i128/lib.hpp"

namespace tifa_libs {
namespace ios128_impl_ {
auto& read(tifa_libs::istream_c auto& is, tifa_libs::u128_c auto& n) {
  static strn int_buf;
  int_buf.reserve(43), n = 0, is >> int_buf;
  for (u32 i = 0; i + 1 < int_buf.size(); i += 2) (n *= 100) += STR2U16[*(u16*)(int_buf.data() + i)];
  if (int_buf.size() & 1) (n *= 10) += int_buf.back() & 15;
  return is;
}
}  // namespace ios128_impl_

auto& operator>>(tifa_libs::istream_c auto& is, tifa_libs::s128_c auto& n) NE {
  bool neg = false;
  if CEXP (requires { is.skip_nnegdigit(); }) neg = (is.skip_nnegdigit().peek() == '-' && is.get_unchk());
  else
    while (!neg && !isdigit(is.peek())) {
      if (is.peek() == '-') neg = true;
      is.get();
    }
  u128 n_ = 0;
  if (ios128_impl_::read(is, n_); neg) n_ = -n_;
  n = (i128)n_;
  return is;
}
auto& operator>>(tifa_libs::istream_c auto& is, tifa_libs::u128_c auto& n) NE {
  if CEXP (requires { is.skip_ndigit(); }) is.skip_ndigit();
  else
    while (!isdigit(is.peek())) is.get();
  return ios128_impl_::read(is, n);
}
auto& operator<<(tifa_libs::ostream_c auto& os, tifa_libs::u128_c auto n) NE {
  static strn int_buf(40, '\0');
  auto it = end(int_buf);
  do *(--(it)) = chr(n % 10) | '0';
  while (n /= 10);
  return os << int_buf.substr(usz(it - begin(int_buf)));
}
auto& operator<<(tifa_libs::ostream_c auto& os, tifa_libs::s128_c auto n) NE {
  if (n < 0) return os << '-' << -(u128)n;
  return os << (u128)n;
}

}  // namespace tifa_libs
#line 2 "src/io/pair/lib.hpp"

#line 4 "src/io/pair/lib.hpp"

namespace tifa_libs {

template <class T, class U>
auto& operator>>(tifa_libs::istream_c auto& is, std::pair<T, U>& p) NE { return is >> p.first >> p.second; }
template <class T, class U>
auto& operator<<(tifa_libs::ostream_c auto& os, std::pair<T, U> CR p) NE { return os << p.first << ' ' << p.second; }

}  // namespace tifa_libs
#line 2 "src/io/tuple/lib.hpp"

#line 4 "src/io/tuple/lib.hpp"

namespace tifa_libs {

template <class... Ts>
auto& operator>>(tifa_libs::istream_c auto& is, std::tuple<Ts...>& p) NE {
  std::apply([&](Ts&... ts) NE { (is >> ... >> ts); }, p);
  return is;
}
template <class... Ts>
auto& operator<<(tifa_libs::ostream_c auto& os, std::tuple<Ts...> CR p) NE {
  std::apply([&, n = 0](Ts const&... ts) mutable NE { ((os << ts << (++n != sizeof...(Ts) ? " " : "")), ...); }, p);
  return os;
}

}  // namespace tifa_libs
#line 7 "test/cpv_local/base.hpp"

namespace tifa_libs {

namespace detail__ {

template <class T>
strn to_str(T CR x) NE {
  std::stringstream ss;
  ss << std::fixed << std::setprecision(12) << x;
  auto str = ss.str();
  retif_((str.length() <= 1024), str, std::format("{}... (length = {})", str.substr(0, 1024), std::to_string(str.length())));
}

template <class T, class... Ts>
void check_(strnv pretty_func, strnv got_str, T CR got, strnv want_str, T CR want, Ts... param) {
  if CEXP (sizeof...(param) == 0) {
    if (got != want) throw std::runtime_error(std::format("{}: got \"{}\" = {}, want \"{}\" = {}", pretty_func, got_str, to_str(got), want_str, to_str(want)));
  } else {
    if (got != want) throw std::runtime_error(std::format("{}: got \"{}\" = {}, want \"{}\" = {} with", pretty_func, got_str, to_str(got), want_str, to_str(want)) + (std::format(" {} = {};", param.first, ::tifa_libs::detail__::to_str(param.second)) + ...));
  }
}

template <class... Ts>
void check_bool_(strnv pretty_func, strnv expression, bool res, Ts... param) {
  if CEXP (sizeof...(param) == 0) {
    if (!res) throw std::runtime_error(std::format("{} :\"{}\" failed", pretty_func, expression));
  } else {
    if (!res) throw std::runtime_error(std::format("{} :\"{}\" failed with", pretty_func, expression) + (std::format(" {} = {};", param.first, ::tifa_libs::detail__::to_str(param.second)) + ...));
  }
}

}  // namespace detail__

template <class clock_t = std::chrono::high_resolution_clock, class duration_t = std::chrono::microseconds>
requires specialized_from_v<duration_t, std::chrono::duration>
struct timer {
  void tic(int line_num) NE {
    s_line_num = line_num;
    const std::lock_guard<std::mutex> lock(s_clock_mutex);
    s_clock_start = clock_t::now();
  }
  void tac() NE {
    const std::lock_guard<std::mutex> lock(s_clock_mutex);
    s_clock_end = clock_t::now();
  }
  auto passed() CNE { return std::chrono::duration_cast<duration_t>(s_clock_end - s_clock_start); }
  operator strn() { return std::format("{} passed in line {}", passed(), s_line_num); }

 private:
  std::mutex s_clock_mutex;
  std::chrono::time_point<clock_t> s_clock_start, s_clock_end;
  int s_line_num;
};
inline timer default_timer;

#define timer_(...)                         \
  ::tifa_libs::default_timer.tic(__LINE__); \
  __VA_ARGS__;                              \
  ::tifa_libs::default_timer.tac();         \
  std::cerr << (strn)::tifa_libs::default_timer << '\n'

#define check(got, want, ...) ::tifa_libs::detail__::check_(__PRETTY_FUNCTION__, #got, got, #want, want __VA_OPT__(, ) __VA_ARGS__)
#define check_bool(expression, ...) ::tifa_libs::detail__::check_bool_(__PRETTY_FUNCTION__, #expression, expression __VA_OPT__(, ) __VA_ARGS__)
#define check_param(x) \
  std::pair<std::string, decltype(x)> { #x, x }

}  // namespace tifa_libs
#line 6 "test/cpv_local/edh/hamming.cpp"

using namespace tifa_libs;
rand_gen<dbitset::word_t> g;

void test(u64 n) {
  dbitset s(n, g);

  timer_(auto v = hamming::encode(s));
  auto m = v.size() - n - 1;
  check_bool(v.size() <= (1_u64 << m), check_param(n), check_param(m), check_param(s.to_string()), check_param(v.to_string()));

  timer_(auto t1 = hamming::decode<false>(v));
  check(t1.to_string(), s.to_string(), check_param(v.to_string()));

  if (v.size() > 1) {
    auto v2 = v;
    rand_gen<u64> g2(1, v.size() - 1);
    auto pos = g2();
    v2.flip(pos);

    timer_(auto t2 = hamming::decode<true>(v2));
    check(v2.to_string(), v.to_string(), check_param(pos));
    check_bool(t2.has_value(), check_param(pos), check_param(s.to_string()), check_param(v.to_string()));
    check(t2->to_string(), s.to_string(), check_param(pos), check_param(v.to_string()));
  }
}

int main() {
  flt_ (u32, i, 0, 20) {
    timer_(test(i));
  }
  flt_ (u32, i, 2, 10) {
    timer_(test((1 << i) - (i + 1)));
  }
  timer_(test(1000));
  timer_(test(10000));
  timer_(test(200000));
  timer_(test(500000));
  timer_(test(100000));
  timer_(test(200000));
  timer_(test(500000));
  timer_(test(1000000));
  timer_(test(2000000));
  timer_(test(5000000));
}
Back to top page