library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub maspypy/library

:heavy_check_mark: test/5_ai_generated_test/intervals_fast.test.cpp

Depends on

Code

#include "my_template.hpp"
#include "other/io.hpp"
#include "ds/intervals.hpp"

// 対象: ds/intervals.hpp の Intervals_Fast<long long>。
// 現行 API の set, get(ERASE=true/false), get_all, enumerate_range,
// enumerate_all, total_num, total_len を検証する。
//
// 独立 oracle: 各座標の値をそのまま vector に保持する。
// 隣接する同値要素をまとめた極大区間が enumerate/get の期待値となる。
// 代入・削除後の区間数と非 none の長さ合計も、配列から再計算する。
//
// 狙う不具合: 半開区間の off-by-one、左右境界での分割・併合漏れ、
// none_val への代入や get(...,true) による区間消去後の集計値破損、
// FastSet の 64 要素境界をまたぐ区間の列挙漏れ、早期終了の誤動作。
// N=0 での構築は先頭に境界 0 を挿入する実装の対象外とし、N>=1 のみ試す。
// 乱数は mt19937_64 の固定 seed 0x1A7E4A15ULL を使用し、CIで再現可能。

namespace {
using i64 = long long;
using Run = tuple<int, int, i64>;
constexpr i64 NONE = -(1LL << 50);

[[noreturn]] void fail(int n, int step, const string& op, const string& why) {
  cerr << "Intervals_Fast FAILED: n=" << n << " step=" << step << " op=" << op
       << " reason=" << why << '\n';
  abort();
}

struct Tester {
  int n;
  int step = 0;
  string op = "initial";
  vector<i64> a;
  Intervals_Fast<i64> ds;
  mt19937_64& rng;

  Tester(int n_, mt19937_64& rng_)
      : n(n_), a(n_, NONE), ds(n_, NONE), rng(rng_) {
    check();
  }

  void require(bool p, const string& message) {
    if (!p) fail(n, step, op, message);
  }

  vector<Run> runs() const {
    vector<Run> result;
    for (int l = 0; l < n;) {
      int r = l + 1;
      while (r < n && a[r] == a[l]) ++r;
      result.emplace_back(l, r, a[l]);
      l = r;
    }
    return result;
  }

  void check() {
    const auto expected = runs();
    int expected_num = 0, expected_len = 0;
    for (const auto& [l, r, x] : expected) {
      if (x != NONE) {
        ++expected_num;
        expected_len += r - l;
      }
    }
    require(ds.total_num == expected_num, "total_num");
    require(ds.total_len == expected_len, "total_len");
    require(ds.get_all() == a, "get_all");

    vector<Run> actual;
    ds.enumerate_all([&](int l, int r, i64 x, bool& end) {
      require(!end, "unexpected end flag in enumerate_all");
      actual.emplace_back(l, r, x);
    });
    require(
        actual == expected, "enumerate_all: maximal intervals / boundaries");

    // 全座標で get の返す区間が極大であることを検査する。
    for (const auto& [l, r, x] : expected) {
      for (int i = l; i < r; ++i) {
        const auto got = ds.get(i);
        require(got == Run(l, r, x), "get at i=" + to_string(i));
      }
    }

    // [L,R) の端点、L==R、非整列区間、および早期終了を検査する。
    const int L = int(rng() % (n + 1));
    const int R = L + int(rng() % (n - L + 1));
    vector<Run> clipped;
    for (const auto& [l, r, x] : expected) {
      if (max(l, L) < min(r, R)) {
        clipped.emplace_back(max(l, L), min(r, R), x);
      }
    }
    vector<Run> got;
    ds.enumerate_range(L, R, [&](int l, int r, i64 x, bool& end) {
      require(!end, "unexpected end flag in enumerate_range");
      got.emplace_back(l, r, x);
    });
    require(got == clipped,
        "enumerate_range [" + to_string(L) + "," + to_string(R) + ")");

    got.clear();
    const size_t limit = 1 + size_t(rng() % 3);
    ds.enumerate_range(L, R, [&](int l, int r, i64 x, bool& end) {
      got.emplace_back(l, r, x);
      if (got.size() == limit) end = true;
    });
    if (clipped.size() > limit) clipped.resize(limit);
    require(got == clipped, "enumerate_range early termination");
  }

  void set(int l, int r, i64 x) {
    op = "set(" + to_string(l) + "," + to_string(r) + "," + to_string(x) + ")";
    ds.set(l, r, x);
    for (int i = l; i < r; ++i) a[i] = x;
    ++step;
    check();
  }

  void get_and_maybe_erase(int i, bool erase) {
    op = "get(" + to_string(i) + ",ERASE=" + to_string(erase) + ")";
    int l = i, r = i + 1;
    while (l > 0 && a[l - 1] == a[i]) --l;
    while (r < n && a[r] == a[i]) ++r;
    const i64 old = a[i];
    const auto got = ds.get(i, erase);
    require(got == Run(l, r, old), "returned interval before erase");
    if (erase && old != NONE) {
      for (int j = l; j < r; ++j) a[j] = NONE;
    }
    ++step;
    check();
  }
};

void run_case(int n, mt19937_64& rng) {
  Tester t(n, rng);
  const i64 V[] = {NONE, -1000000000000LL, -17, -1, 0, 1, 17, 1000000000000LL};
  auto pick = [&]() -> i64 { return V[rng() % (sizeof(V) / sizeof(V[0]))]; };

  // 同じ値の再代入、全面消去、片側境界、空区間を明示的に踏む。
  t.set(0, n, 17);
  t.set(0, n, 17);
  t.set(0, n, NONE);
  t.set(0, 0, 1);
  t.set(n, n, 1);
  t.set(0, n, -17);
  t.set(n / 4, (3 * n) / 4, NONE);
  t.set(n / 4, (3 * n) / 4, 0);
  t.get_and_maybe_erase(n / 2, true);
  t.get_and_maybe_erase(n / 2, true);

  // 64-ary FastSet の単語・階層境界で、細かな区間の分割・再結合を確認。
  for (int i : {0, 1, 62, 63, 64, 65, 126, 127, 128, 129, 190, 191, 192, 193,
           254, 255, 256}) {
    if (i < n) t.set(i, i + 1, (i % 2 ? -1 : 1));
  }
  for (int i = 0; i < n; ++i) t.set(i, i + 1, (i % 2 ? 1 : 0));
  t.get_and_maybe_erase(n - 1, true);
  t.get_and_maybe_erase(0, true);
  t.set(0, n, NONE);

  // 乱択の区間代入・極大区間消去・照会を混在させる。
  for (int rep = 0; rep < 850; ++rep) {
    int kind = int(rng() % 12);
    if (kind <= 8) {
      int l = int(rng() % (n + 1));
      int r = int(rng() % (n + 1));
      if (l > r) swap(l, r);
      if (kind == 0) l = 0;
      if (kind == 1) r = n;
      if (kind == 2) r = l;
      t.set(l, r, pick());
    } else {
      const int i = int(rng() % n);
      t.get_and_maybe_erase(i, kind == 9 || kind == 10);
    }
  }
}
}  // namespace

int main() {
  mt19937_64 rng(0x1A7E4A15ULL);
  for (int n : {1, 2, 3, 4, 7, 8, 9, 31, 32, 33, 63, 64, 65, 66, 127, 128, 129,
           191, 192, 193, 255, 256, 257}) {
    run_case(n, rng);
  }
  cerr << "PASS: Intervals_Fast independent array oracle\n";
  return 0;
}
#line 1 "my_template.hpp"
// Source: https://github.com/maspypy/library/blob/main/my_template.hpp
#if defined(USE_PCH)
#include <my_template_compiled.hpp>

#if defined(__GNUC__)
#pragma GCC optimize("Ofast,unroll-loops")
#if !defined(MASPY_NON_AVX2)
#pragma GCC target("avx2,popcnt")
#endif
#endif

#else  // MASPY_TEMPLATE_BODY
#include <bits/stdc++.h>
#include <cassert>

#if defined(__GNUC__)
#pragma GCC optimize("Ofast,unroll-loops")
#endif

using namespace std;

using ll = long long;
using u8 = uint8_t;
using u16 = uint16_t;
using u32 = uint32_t;
using u64 = uint64_t;
using i128 = __int128;
using u128 = unsigned __int128;
using f128 = __float128;

template <class>
constexpr bool dependent_false = false;

template <class T>
constexpr T infty = [] {
  static_assert(dependent_false<T>, "infty<T> is not defined");
  return T{};
}();
template <>
constexpr int infty<int> = 1'010'000'000;
template <>
constexpr ll infty<ll> = 4'040'000'000'000'000'000;
template <>
constexpr u32 infty<u32> = infty<int>;
template <>
constexpr u64 infty<u64> = infty<ll>;
template <>
constexpr i128 infty<i128> = i128(infty<ll>) * 4'000'000'000'000'000'000;
template <>
constexpr double infty<double> = infty<i128>;
template <>
constexpr long double infty<long double> = infty<i128>;

using pi = pair<ll, ll>;
using vi = vector<ll>;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using pq_max = priority_queue<T>;
template <class T>
using pq_min = priority_queue<T, vector<T>, greater<T>>;

#define vv(type, name, h, ...) \
  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...)   \
  vector<vector<vector<type>>> name( \
      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)       \
  vector<vector<vector<vector<type>>>> name( \
      a, vector<vector<vector<type>>>(       \
             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR1_R(a) for (ll i = ll(a) - 1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = ll(a) - 1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = ll(b) - 1; i >= ll(a); --i)
#define overload3(a, b, c, d, ...) d
#define FOR(...) overload3(__VA_ARGS__, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) overload3(__VA_ARGS__, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)

#define all(x) (x).begin(), (x).end()
#define len(x) ll(x.size())
#define elif else if

#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second

#define stoi stoll

// require y > 0
template <typename T>
T floor(T x, T y) {
  return x / y - (x % y < 0);
}

// require y > 0
template <typename T>
T ceil(T x, T y) {
  return (x / y) + (x % y > 0);
}

// require y > 0
template <typename T>
T bmod(T x, T y) {
  T r = x % y;
  return (r < 0 ? r + y : r);
}

// require y > 0
template <typename T>
pair<T, T> divmod(T x, T y) {
  T q = x / y, r = x % y;
  if (r < 0) --q, r += y;
  return {q, r};
}

constexpr auto TEN = [] {
  array<u64, 20> A{};
  A[0] = 1;
  for (int i = 1; i < 20; ++i) A[i] = 10 * A[i - 1];
  return A;
}();

template <typename T, typename U>
T SUM(const U &A) {
  return std::accumulate(A.begin(), A.end(), T{});
}

#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
template <class C, class T>
inline long long LB(const C &c, const T &x) {
  return lower_bound(c.begin(), c.end(), x) - c.begin();
}
template <class C, class T>
inline long long UB(const C &c, const T &x) {
  return upper_bound(c.begin(), c.end(), x) - c.begin();
}
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())

template <typename T>
T POP(deque<T> &que) {
  T a = que.front();
  que.pop_front();
  return a;
}
template <class T, class Container, class Compare>
T POP(priority_queue<T, Container, Compare> &que) {
  T a = que.top();
  que.pop();
  return a;
}
template <typename T>
T POP(vc<T> &que) {
  T a = que.back();
  que.pop_back();
  return a;
}

template <typename F>
i128 binary_search(F check, i128 ok, i128 ng, bool check_ok = true) {
  if (check_ok) assert(check(ok));
  while (1) {
    i128 x = (ok + ng) / 2;
    if (x == ok || x == ng) break;
    (check(x) ? ok : ng) = x;
  }
  return ok;
}

template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
  FOR(iter) {
    double x = (ok + ng) / 2;
    (check(x) ? ok : ng) = x;
  }
  return (ok + ng) / 2;
}

template <class T, class S>
inline bool chmax(T &a, const S &b) {
  T c = max<T>(a, b);
  bool changed = (c != a);
  a = c;
  return changed;
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
  T c = min<T>(a, b);
  bool changed = (c != a);
  a = c;
  return changed;
}

// bit operations
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
int popcnt_sgn(int x) { return (__builtin_parity(unsigned(x)) & 1 ? -1 : 1); }
int popcnt_sgn(u32 x) { return (__builtin_parity(x) & 1 ? -1 : 1); }
int popcnt_sgn(ll x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
int popcnt_sgn(u64 x) { return (__builtin_parityll(x) & 1 ? -1 : 1); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T kth_bit(int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return T(1) << k;
}
template <typename T>
bool has_kth_bit(T x, int k) {
  assert(0 <= k && k < int(8 * sizeof(T)));
  return x >> k & 1;
}

template <typename T>
struct all_bit {
  static_assert(is_integral<T>::value);
  T s;
  all_bit(T s) : s(s) { assert(s >= 0); }
  struct iter {
    T s;
    int operator*() const { return lowbit(s); }
    void operator++() { s &= s - 1; }
    bool operator!=(nullptr_t) const { return s; }
  };
  iter begin() const { return {s}; }
  nullptr_t end() const { return nullptr; }
};

template <typename T>
struct all_subset {
  static_assert(is_integral<T>::value);
  T s;
  all_subset(T s) : s(s) { assert(s >= 0); }
  struct iter {
    T s, t;
    bool done = false;
    T operator*() const { return t; }
    void operator++() {
      done = (t == 0);
      t = (t - 1) & s;
    }
    bool operator!=(nullptr_t) const { return !done; }
  };
  iter begin() const { return {s, s}; }
  nullptr_t end() const { return nullptr; }
};

constexpr u64 full_mask(int n) {
  assert(0 <= n && n <= 64);
  return n == 64 ? -1ULL : (1ULL << n) - 1;
}

u64 bit_reverse(u64 x) {
  x = ((x & 0x5555555555555555ULL) << 1) | ((x >> 1) & 0x5555555555555555ULL);
  x = ((x & 0x3333333333333333ULL) << 2) | ((x >> 2) & 0x3333333333333333ULL);
  x = ((x & 0x0f0f0f0f0f0f0f0fULL) << 4) | ((x >> 4) & 0x0f0f0f0f0f0f0f0fULL);
  x = ((x & 0x00ff00ff00ff00ffULL) << 8) | ((x >> 8) & 0x00ff00ff00ff00ffULL);
  x = ((x & 0x0000ffff0000ffffULL) << 16) | ((x >> 16) & 0x0000ffff0000ffffULL);
  x = (x << 32) | (x >> 32);
  return x;
}

// ? は -1
vc<int> s_to_vi(const string &S, char first_char) {
  vc<int> A(S.size());
  FOR(i, S.size()) { A[i] = (S[i] != '?' ? S[i] - first_char : -1); }
  return A;
}

template <typename T, typename U>
vc<T> cumsum(const vc<U> &A, int off = 1) {
  int N = A.size();
  vc<T> B(N + 1);
  FOR(i, N) { B[i + 1] = B[i] + A[i]; }
  if (off == 0) B.erase(B.begin());
  return B;
}

// stable sort
template <typename T>
vc<int> argsort(const vc<T> &A) {
  vc<int> ids(len(A));
  iota(all(ids), 0);
  sort(all(ids),
      [&](int i, int j) { return (A[i] == A[j] ? i < j : A[i] < A[j]); });
  return ids;
}

// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
  vc<T> B(len(I));
  FOR(i, len(I)) B[i] = A[I[i]];
  return B;
}

template <typename T, typename... Vectors>
void concat(vc<T> &first, const Vectors &...others) {
  size_t n = first.size() + (others.size() + ... + 0);
  if (n > first.capacity()) {
    first.reserve(max(n, 2 * first.capacity()));
  }
  (first.insert(first.end(), others.begin(), others.end()), ...);
}

// i128
template <class T, enable_if_t<is_same_v<T, i128>, int> = 0>
constexpr i128 abs(T x) {
  return x < 0 ? -x : x;
}

constexpr i128 gcd(i128 a, i128 b) {
  while (b != 0) {
    i128 c = a % b;
    a = b, b = c;
  }
  return abs(a);
}
#endif  // MASPY_TEMPLATE_BODY
#line 1 "other/io.hpp"
// Source: https://github.com/maspypy/library/blob/main/other/io.hpp
#define FASTIO

// https://judge.yosupo.jp/submission/21623
namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf
uint32_t pil = 0, pir = 0, por = 0;
bool input_eof = false;

template <class T>
constexpr bool is_signed_integer_v = is_signed_v<T> || is_same_v<T, i128>;

template <class T>
struct unsigned_integer {
  using type = make_unsigned_t<T>;
};
template <>
struct unsigned_integer<i128> {
  using type = u128;
};
template <>
struct unsigned_integer<u128> {
  using type = u128;
};
template <class T>
using unsigned_integer_t = typename unsigned_integer<T>::type;

[[noreturn]] inline void input_error(const char *message) {
  fputs(message, stderr);
  fputc('\n', stderr);
  exit(EXIT_FAILURE);
}

struct Pre {
  char num[10000][4];
  constexpr Pre() : num() {
    for (int i = 0; i < 10000; i++) {
      int n = i;
      for (int j = 3; j >= 0; j--) {
        num[i][j] = n % 10 | '0';
        n /= 10;
      }
    }
  }
} constexpr pre;

inline void load() {
  uint32_t n = pir - pil;
  memmove(ibuf, ibuf + pil, n);
  pil = 0;
  pir = n;
  if (input_eof) return;

  pir += fread(ibuf + pir, 1, SZ - pir, stdin);
  if (ferror(stdin)) input_error("fastio: input error");
  if (feof(stdin)) {
    input_eof = true;
    // Allows the last token to end exactly at EOF without a trailing
    // whitespace.
    if (pir < SZ) ibuf[pir++] = '\n';
  }
}

inline char get_char() {
  if (pil == pir) {
    load();
    if (pil == pir) input_error("fastio: unexpected EOF");
  }
  return ibuf[pil++];
}

inline void flush() {
  fwrite(obuf, 1, por, stdout);
  por = 0;
}

void rd(char &c) {
  do c = get_char();
  while (isspace(static_cast<unsigned char>(c)));
}

void rd(string &x) {
  x.clear();
  char c;
  do c = get_char();
  while (isspace(static_cast<unsigned char>(c)));
  do {
    x += c;
    c = get_char();
  } while (!isspace(static_cast<unsigned char>(c)));
}

template <typename T>
void rd_real(T &x) {
  string s;
  rd(s);
  x = stod(s);
}

template <typename T>
void rd_integer_slow(T &x) {
  char c;
  do c = get_char();
  while (c < '-');
  bool minus = 0;
  if constexpr (is_signed_integer_v<T>) {
    if (c == '-') {
      minus = 1, c = get_char();
    }
  }
  x = 0;
  assert('0' <= c && c <= '9');
  while ('0' <= c && c <= '9') {
    x = x * 10 + (c & 15), c = get_char();
  }
  assert(isspace(static_cast<unsigned char>(c)));
  if constexpr (is_signed_integer_v<T>) {
    if (minus) x = -x;
  }
}

template <typename T>
void rd_integer(T &x) {
  if (pil + 100 > pir) {
    load();
    if (pil + 100 > pir) {
      rd_integer_slow(x);
      return;
    }
  }
  char c;
  do c = ibuf[pil++];
  while (c < '-');
  bool minus = 0;
  if constexpr (is_signed_integer_v<T>) {
    if (c == '-') {
      minus = 1, c = ibuf[pil++];
    }
  }
  x = 0;
  assert('0' <= c && c <= '9');
  while ('0' <= c && c <= '9') {
    x = x * 10 + (c & 15), c = ibuf[pil++];
  }
  assert(isspace(static_cast<unsigned char>(c)));
  if constexpr (is_signed_integer_v<T>) {
    if (minus) x = -x;
  }
}

template <class T>
enable_if_t<is_integral_v<T> || is_same_v<T, i128> || is_same_v<T, u128>> rd(
    T &x) {
  rd_integer(x);
}

template <class T>
enable_if_t<is_floating_point_v<T> || is_same_v<T, f128>> rd(T &x) {
  rd_real(x);
}

template <class T, class U>
void rd(pair<T, U> &p) {
  rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T>
void rd_tuple(T &t) {
  if constexpr (N < tuple_size<T>::value) {
    auto &x = get<N>(t);
    rd(x);
    rd_tuple<N + 1>(t);
  }
}
template <class... T>
void rd(tuple<T...> &tpl) {
  rd_tuple(tpl);
}

template <class T, size_t N>
void rd(array<T, N> &x) {
  for (auto &d : x) rd(d);
}
template <class T>
void rd(vc<T> &x) {
  for (auto &d : x) rd(d);
}

template <class... T>
void read(T &...x) {
  (rd(x), ...);
}

inline void wt_range(const char *s, size_t n) {
  size_t i = 0;
  while (i < n) {
    if (por == SZ) flush();
    size_t chunk = min(n - i, (size_t)(SZ - por));
    memcpy(obuf + por, s + i, chunk);
    por += chunk;
    i += chunk;
  }
}

void wt(const char c) {
  if (por == SZ) flush();
  obuf[por++] = c;
}
void wt(const char *s) { wt_range(s, strlen(s)); }
void wt(const string &s) { wt_range(s.data(), s.size()); }

template <typename T>
void wt_integer(T x) {
  if (por > SZ - 100) flush();
  using U = unsigned_integer_t<T>;
  U y = static_cast<U>(x);
  if constexpr (is_signed_integer_v<T>) {
    if (x < 0) {
      obuf[por++] = '-';
      y = U(0) - y;
    }
  }
  int outi;
  for (outi = 96; y >= 10000; outi -= 4) {
    memcpy(out + outi, pre.num[y % 10000], 4);
    y /= 10000;
  }
  if (y >= 1000) {
    memcpy(obuf + por, pre.num[y], 4);
    por += 4;
  } else if (y >= 100) {
    memcpy(obuf + por, pre.num[y] + 1, 3);
    por += 3;
  } else if (y >= 10) {
    int q = (y * 103) >> 10;
    obuf[por] = q | '0';
    obuf[por + 1] = (y - q * 10) | '0';
    por += 2;
  } else
    obuf[por++] = y | '0';
  memcpy(obuf + por, out + outi + 4, 96 - outi);
  por += 96 - outi;
}

template <typename T>
inline void wt_real(T x) {
  static char buf[1000];
  int n = std::snprintf(buf, sizeof(buf), "%.15f", (double)x);
  wt_range(buf, (size_t)n);
}

template <class T>
enable_if_t<is_integral_v<T> || is_same_v<T, i128> || is_same_v<T, u128>> wt(
    T x) {
  wt_integer(x);
}

template <class T>
enable_if_t<is_floating_point_v<T> || is_same_v<T, f128>> wt(T x) {
  wt_real(x);
}

inline void wt(bool b) { wt(static_cast<char>('0' + (b ? 1 : 0))); }

template <class T, class U>
void wt(const pair<T, U> &val) {
  wt(val.first);
  wt(' ');
  wt(val.second);
}
template <size_t N = 0, typename T>
void wt_tuple(const T &t) {
  if constexpr (N < tuple_size<T>::value) {
    if constexpr (N > 0) wt(' ');
    wt(get<N>(t));
    wt_tuple<N + 1>(t);
  }
}
template <class... T>
void wt(const tuple<T...> &tpl) {
  wt_tuple(tpl);
}
template <class T, size_t S>
void wt(const array<T, S> &val) {
  auto n = val.size();
  for (size_t i = 0; i < n; i++) {
    if (i) wt(' ');
    wt(val[i]);
  }
}
template <class T>
void wt(const vector<T> &val) {
  auto n = val.size();
  for (size_t i = 0; i < n; i++) {
    if (i) wt(' ');
    wt(val[i]);
  }
}

void print() { wt('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&...tail) {
  wt(forward<Head>(head));
  ((wt(' '), wt(forward<Tail>(tail))), ...);
  wt('\n');
}

// gcc expansion. called automaticall after main.
void __attribute__((destructor)) _d() { flush(); }
}  // namespace fastio
using fastio::flush;
using fastio::print;
using fastio::read;

#if defined(LOCAL)
#define HDR "[DEBUG:", __func__, __LINE__, "]"
#define SHOW(...)                                                         \
  SHOW_IMPL(__VA_ARGS__, SHOW8, SHOW7, SHOW6, SHOW5, SHOW4, SHOW3, SHOW2, \
            SHOW1)                                                        \
  (__VA_ARGS__)
#define SHOW_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, NAME, ...) NAME
#define SHOW1(x) print(HDR, #x, "=", (x)), flush()
#define SHOW2(x, y) print(HDR, #x, "=", (x), #y, "=", (y)), flush()
#define SHOW3(x, y, z) \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z)), flush()
#define SHOW4(x, y, z, w) \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w)), flush()
#define SHOW5(x, y, z, w, v)                                                  \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w), #v, "=", \
        (v)),                                                                 \
      flush()
#define SHOW6(x, y, z, w, v, u)                                               \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w), #v, "=", \
        (v), #u, "=", (u)),                                                   \
      flush()
#define SHOW7(x, y, z, w, v, u, t)                                            \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w), #v, "=", \
        (v), #u, "=", (u), #t, "=", (t)),                                     \
      flush()
#define SHOW8(x, y, z, w, v, u, t, s)                                         \
  print(HDR, #x, "=", (x), #y, "=", (y), #z, "=", (z), #w, "=", (w), #v, "=", \
        (v), #u, "=", (u), #t, "=", (t), #s, "=", (s)),                       \
      flush()
#else
#define SHOW(...)
#endif

#define INT(...)   \
  int __VA_ARGS__; \
  read(__VA_ARGS__)
#define LL(...)   \
  ll __VA_ARGS__; \
  read(__VA_ARGS__)
#define U32(...)   \
  u32 __VA_ARGS__; \
  read(__VA_ARGS__)
#define U64(...)   \
  u64 __VA_ARGS__; \
  read(__VA_ARGS__)
#define STR(...)      \
  string __VA_ARGS__; \
  read(__VA_ARGS__)
#define CHAR(...)   \
  char __VA_ARGS__; \
  read(__VA_ARGS__)
#define DBL(...)      \
  double __VA_ARGS__; \
  read(__VA_ARGS__)

#define VEC(type, name, size) \
  vector<type> name(size);    \
  read(name)
#define VV(type, name, h, w)                     \
  vector<vector<type>> name(h, vector<type>(w)); \
  read(name)

void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
void YA(bool t = 1) { print(t ? "YA" : "TIDAK"); }
void TIDAK(bool t = 1) { YA(!t); }
void Alice(bool t = 1) { print(t ? "Alice" : "Bob"); }
void Bob(bool t = 1) { Alice(!t); }
#line 1 "ds/intervals.hpp"
// Source: https://github.com/maspypy/library/blob/main/ds/intervals.hpp
#line 1 "ds/fastset.hpp"
// Source: https://github.com/maspypy/library/blob/main/ds/fastset.hpp
// 64-ary tree
// space: (N/63) * u64
struct FastSet {
  static constexpr u32 B = 64;
  int n = 0, log = 0;
  vvc<u64> seg;

  FastSet() {}
  FastSet(int n) { build(n); }

  int size() { return n; }

  void fill_one() {
    int cur = n;
    for (auto& vs : seg) {
      int p = cur / B, q = cur % B;
      FOR(i, p) vs[i] = -1ull;
      if (q) vs[p] = full_mask(q);
      cur = (cur + B - 1) / B;
    }
  }

  template <typename F>
  FastSet(int n, F f) {
    build(n, f);
  }

  void build(int m) {
    seg.clear();
    n = m;
    do {
      seg.push_back(vc<u64>((m + B - 1) / B));
      m = (m + B - 1) / B;
    } while (m > 1);
    log = len(seg);
  }
  template <typename F>
  void build(int n, F f) {
    build(n);
    FOR(i, n) { seg[0][i / B] |= u64(bool(f(i))) << (i % B); }
    FOR(h, log - 1) {
      FOR(i, len(seg[h])) {
        seg[h + 1][i / B] |= u64(bool(seg[h][i])) << (i % B);
      }
    }
  }

  bool operator[](int i) const {
    assert(0 <= i && i < n);
    return seg[0][i / B] >> (i % B) & 1;
  }
  void insert(int i) {
    assert(0 <= i && i < n);
    for (int h = 0; h < log; h++) {
      u64& x = seg[h][i / B];
      u64 mask = u64(1) << (i % B);
      if (x & mask) return;
      x |= mask;
      i /= B;
    }
  }
  void add(int i) { insert(i); }
  void erase(int i) {
    assert(0 <= i && i < n);
    for (int h = 0; h < log; h++) {
      u64& x = seg[h][i / B];
      u64 mask = u64(1) << (i % B);
      if (!(x & mask)) return;
      x ^= mask;
      if (x) return;
      i /= B;
    }
  }
  void remove(int i) { erase(i); }

  // min[x,n) or n
  int next(int i) {
    assert(i <= n);
    chmax(i, 0);
    for (int h = 0; h < log; h++) {
      if (i / B == seg[h].size()) break;
      u64 d = seg[h][i / B] >> (i % B);
      if (!d) {
        i = i / B + 1;
        continue;
      }
      i += lowbit(d);
      for (int g = h - 1; g >= 0; g--) {
        i *= B;
        i += lowbit(seg[g][i / B]);
      }
      return i;
    }
    return n;
  }

  // max [0,x], or -1
  int prev(int i) {
    assert(i >= -1);
    if (i >= n) i = n - 1;
    for (int h = 0; h < log; h++) {
      if (i == -1) break;
      u64 d = seg[h][i / B] << (63 - i % B);
      if (!d) {
        i = i / B - 1;
        continue;
      }
      i -= __builtin_clzll(d);
      for (int g = h - 1; g >= 0; g--) {
        i *= B;
        i += topbit(seg[g][i / B]);
      }
      return i;
    }
    return -1;
  }

  bool any(int l, int r) {
    assert(0 <= l && l <= r && r <= n);
    return next(l) < r;
  }

  // [l, r). erase=true のとき、callback 内から this を変更してはいけない。
  template <typename F>
  void enumerate(int l, int r, F f, bool erase = false) {
    bool end = false;
    assert(0 <= l && l <= r && r <= n);
    if (!erase) {
      for (int x = next(l); x < r; x = next(x + 1)) {
        f(x, end);
        if (end) return;
      }
      return;
    }
    for (int x = next(l); x < r;) {
      int w = x / B;
      int lo = max(l, w * int(B)) - w * int(B);
      int hi = min(r, (w + 1) * int(B)) - w * int(B);
      u64 erase_bits = seg[0][w] & (full_mask(hi) & ~full_mask(lo));
      u64 bits = erase_bits;
      while (bits) {
        int k = lowbit(bits);
        f(w * int(B) + k, end);
        bits ^= u64(1) << k;
        assert(!end);  // 未対応
      }
      seg[0][w] ^= erase_bits;
      if (!seg[0][w]) propagate_empty_word(w);
      x = next(min(r, (w + 1) * int(B)));
    }
  }

  void reset() {
    int x = next(0);
    while (x < n) {
      int w = x / B;
      seg[0][w] = 0;
      propagate_empty_word(w);
      x = next(min(n, (w + 1) * int(B)));
    }
  }

  string to_string() {
    string s(n, '?');
    for (int i = 0; i < n; ++i) s[i] = ((*this)[i] ? '1' : '0');
    return s;
  }

 private:
  // seg[0][w] が 0 になった後に呼ぶ。
  void propagate_empty_word(int i) {
    for (int h = 1; h < log; ++h) {
      u64& y = seg[h][i / B];
      u64 mask = u64(1) << (i % B);
      y ^= mask;
      if (y) break;
      i /= B;
    }
  }
};
#line 3 "ds/intervals.hpp"

// FastSet で高速化したもの
template <typename T>
struct Intervals_Fast {
  const int LLIM, RLIM;
  const T none_val;
  // none_val でない区間の個数と長さ合計
  int total_num;
  int total_len;
  vc<T> dat;
  FastSet ss;

  Intervals_Fast(int N, T none_val)
      : LLIM(0),
        RLIM(N),
        none_val(none_val),
        total_num(0),
        total_len(0),
        dat(N, none_val),
        ss(N) {
    ss.insert(0);
  }

  // x を含む区間の情報の取得 l, r, t
  tuple<int, int, T> get(int x, bool ERASE = false) {
    int l = ss.prev(x);
    int r = ss.next(x + 1);
    T t = dat[l];
    if (t != none_val && ERASE) {
      --total_num, total_len -= r - l;
      dat[l] = none_val;
      merge_at(l);
      merge_at(r);
    }
    return {l, r, t};
  }

  // [L, R) 内の全データの取得
  // f(l,r,x)
  template <typename F>
  void enumerate_range(int L, int R, F f, bool ERASE = false) {
    assert(LLIM <= L && L <= R && R <= RLIM);
    if (L == R) return;
    bool end = false;
    if (!ERASE) {
      int l = ss.prev(L);
      while (l < R) {
        int r = ss.next(l + 1);
        f(max(l, L), min(r, R), dat[l], end);
        if (end) return;
        l = r;
      }
      return;
    }
    // 半端なところの分割
    int p = ss.prev(L);
    if (p < L) {
      ss.insert(L);
      dat[L] = dat[p];
      if (dat[L] != none_val) ++total_num;
    }
    p = ss.next(R);
    if (R < p) {
      dat[R] = dat[ss.prev(R)];
      ss.insert(R);
      if (dat[R] != none_val) ++total_num;
    }
    p = L;
    while (p < R) {
      int q = ss.next(p + 1);
      T x = dat[p];
      f(p, q, x, end);
      assert(!end);  // 未対応
      if (dat[p] != none_val) --total_num, total_len -= q - p;
      ss.erase(p);
      p = q;
    }
    ss.insert(L);
    dat[L] = none_val;
  }

  void set(int L, int R, T t) {
    if (L == R) return;
    enumerate_range(L, R, [](int l, int r, T x, bool) -> void {}, true);
    ss.insert(L);
    dat[L] = t;
    if (t != none_val) total_num++, total_len += R - L;
    merge_at(L);
    merge_at(R);
  }

  template <typename F>
  void enumerate_all(F f) {
    enumerate_range(0, RLIM, f, false);
  }

  void merge_at(int p) {
    if (p <= 0 || RLIM <= p) return;
    int q = ss.prev(p - 1);
    if (dat[p] == dat[q]) {
      if (dat[p] != none_val) --total_num;
      ss.erase(p);
    }
  }

  vc<T> get_all() {
    vc<T> res(RLIM, none_val);
    enumerate_all([&](int a, int b, T t, bool) -> void {
      FOR(i, a, b) res[i] = t;
    });
    return res;
  }
};

// https://codeforces.com/contest/1638/problem/E
// 持つ値のタイプ T、座標タイプ X
// コンストラクタでは T none_val を指定する
// 先読み可能なら座圧して fastset の方が速い
template <typename T, typename X = ll>
struct Intervals {
  static constexpr X LLIM = -infty<X>;
  static constexpr X RLIM = infty<X>;
  T none_val;
  // const T none_val;
  // none_val でない区間の個数と長さ合計
  int total_num;
  X total_len;
  map<X, T> dat;

  Intervals(T none_val = 0) : none_val(none_val), total_num(0), total_len(0) {
    dat[LLIM] = none_val;
    dat[RLIM] = none_val;
  }

  // x を含む区間の情報の取得 l, r, t
  tuple<X, X, T> get(X x, bool ERASE = false) {
    auto it2 = dat.upper_bound(x);
    auto it1 = prev(it2);
    auto [l, tl] = *it1;
    auto [r, tr] = *it2;
    if (tl != none_val && ERASE) {
      --total_num, total_len -= r - l;
      dat[l] = none_val;
      merge_at(l);
      merge_at(r);
    }
    return {l, r, tl};
  }

  // [L, R) 内の全データの取得 f(l, r, t, end)
  template <typename F>
  void enumerate_range(X L, X R, F f, bool ERASE = false) {
    assert(LLIM <= L && L <= R && R <= RLIM);
    if (L == R) return;
    bool end = false;
    if (!ERASE) {
      auto it = prev(dat.upper_bound(L));
      while ((*it).fi < R) {
        auto it2 = next(it);
        f(max((*it).fi, L), min((*it2).fi, R), (*it).se, end);
        it = it2;
        if (end) break;
      }
      return;
    }
    // 半端なところの分割
    auto p = prev(dat.upper_bound(L));
    if ((*p).fi < L) {
      dat[L] = (*p).se;
      if (dat[L] != none_val) ++total_num;
    }
    p = dat.lower_bound(R);
    if (R < (*p).fi) {
      T t = (*prev(p)).se;
      dat[R] = t;
      if (t != none_val) ++total_num;
    }
    p = dat.lower_bound(L);
    while (1) {
      if ((*p).fi >= R) break;
      auto q = next(p);
      T t = (*p).se;
      f((*p).fi, (*q).fi, t, end);
      assert(!end);  // 未対応
      if (t != none_val) --total_num, total_len -= (*q).fi - (*p).fi;
      p = dat.erase(p);
    }
    dat[L] = none_val;
  }

  void set(X L, X R, T t) {
    assert(L <= R);
    if (L == R) return;
    enumerate_range(L, R, [](int l, int r, T x, bool) -> void {}, true);
    dat[L] = t;
    if (t != none_val) total_num++, total_len += R - L;
    merge_at(L);
    merge_at(R);
  }

  template <typename F>
  void enumerate_all(F f) {
    enumerate_range(LLIM, RLIM, f, false);
  }

  void merge_at(X p) {
    if (p == LLIM || RLIM == p) return;
    auto itp = dat.lower_bound(p);
    assert((*itp).fi == p);
    auto itq = prev(itp);
    if ((*itp).se == (*itq).se) {
      if ((*itp).se != none_val) --total_num;
      dat.erase(itp);
    }
  }
};
#line 4 "test/5_ai_generated_test/intervals_fast.test.cpp"

// 対象: ds/intervals.hpp の Intervals_Fast<long long>。
// 現行 API の set, get(ERASE=true/false), get_all, enumerate_range,
// enumerate_all, total_num, total_len を検証する。
//
// 独立 oracle: 各座標の値をそのまま vector に保持する。
// 隣接する同値要素をまとめた極大区間が enumerate/get の期待値となる。
// 代入・削除後の区間数と非 none の長さ合計も、配列から再計算する。
//
// 狙う不具合: 半開区間の off-by-one、左右境界での分割・併合漏れ、
// none_val への代入や get(...,true) による区間消去後の集計値破損、
// FastSet の 64 要素境界をまたぐ区間の列挙漏れ、早期終了の誤動作。
// N=0 での構築は先頭に境界 0 を挿入する実装の対象外とし、N>=1 のみ試す。
// 乱数は mt19937_64 の固定 seed 0x1A7E4A15ULL を使用し、CIで再現可能。

namespace {
using i64 = long long;
using Run = tuple<int, int, i64>;
constexpr i64 NONE = -(1LL << 50);

[[noreturn]] void fail(int n, int step, const string& op, const string& why) {
  cerr << "Intervals_Fast FAILED: n=" << n << " step=" << step << " op=" << op
       << " reason=" << why << '\n';
  abort();
}

struct Tester {
  int n;
  int step = 0;
  string op = "initial";
  vector<i64> a;
  Intervals_Fast<i64> ds;
  mt19937_64& rng;

  Tester(int n_, mt19937_64& rng_)
      : n(n_), a(n_, NONE), ds(n_, NONE), rng(rng_) {
    check();
  }

  void require(bool p, const string& message) {
    if (!p) fail(n, step, op, message);
  }

  vector<Run> runs() const {
    vector<Run> result;
    for (int l = 0; l < n;) {
      int r = l + 1;
      while (r < n && a[r] == a[l]) ++r;
      result.emplace_back(l, r, a[l]);
      l = r;
    }
    return result;
  }

  void check() {
    const auto expected = runs();
    int expected_num = 0, expected_len = 0;
    for (const auto& [l, r, x] : expected) {
      if (x != NONE) {
        ++expected_num;
        expected_len += r - l;
      }
    }
    require(ds.total_num == expected_num, "total_num");
    require(ds.total_len == expected_len, "total_len");
    require(ds.get_all() == a, "get_all");

    vector<Run> actual;
    ds.enumerate_all([&](int l, int r, i64 x, bool& end) {
      require(!end, "unexpected end flag in enumerate_all");
      actual.emplace_back(l, r, x);
    });
    require(
        actual == expected, "enumerate_all: maximal intervals / boundaries");

    // 全座標で get の返す区間が極大であることを検査する。
    for (const auto& [l, r, x] : expected) {
      for (int i = l; i < r; ++i) {
        const auto got = ds.get(i);
        require(got == Run(l, r, x), "get at i=" + to_string(i));
      }
    }

    // [L,R) の端点、L==R、非整列区間、および早期終了を検査する。
    const int L = int(rng() % (n + 1));
    const int R = L + int(rng() % (n - L + 1));
    vector<Run> clipped;
    for (const auto& [l, r, x] : expected) {
      if (max(l, L) < min(r, R)) {
        clipped.emplace_back(max(l, L), min(r, R), x);
      }
    }
    vector<Run> got;
    ds.enumerate_range(L, R, [&](int l, int r, i64 x, bool& end) {
      require(!end, "unexpected end flag in enumerate_range");
      got.emplace_back(l, r, x);
    });
    require(got == clipped,
        "enumerate_range [" + to_string(L) + "," + to_string(R) + ")");

    got.clear();
    const size_t limit = 1 + size_t(rng() % 3);
    ds.enumerate_range(L, R, [&](int l, int r, i64 x, bool& end) {
      got.emplace_back(l, r, x);
      if (got.size() == limit) end = true;
    });
    if (clipped.size() > limit) clipped.resize(limit);
    require(got == clipped, "enumerate_range early termination");
  }

  void set(int l, int r, i64 x) {
    op = "set(" + to_string(l) + "," + to_string(r) + "," + to_string(x) + ")";
    ds.set(l, r, x);
    for (int i = l; i < r; ++i) a[i] = x;
    ++step;
    check();
  }

  void get_and_maybe_erase(int i, bool erase) {
    op = "get(" + to_string(i) + ",ERASE=" + to_string(erase) + ")";
    int l = i, r = i + 1;
    while (l > 0 && a[l - 1] == a[i]) --l;
    while (r < n && a[r] == a[i]) ++r;
    const i64 old = a[i];
    const auto got = ds.get(i, erase);
    require(got == Run(l, r, old), "returned interval before erase");
    if (erase && old != NONE) {
      for (int j = l; j < r; ++j) a[j] = NONE;
    }
    ++step;
    check();
  }
};

void run_case(int n, mt19937_64& rng) {
  Tester t(n, rng);
  const i64 V[] = {NONE, -1000000000000LL, -17, -1, 0, 1, 17, 1000000000000LL};
  auto pick = [&]() -> i64 { return V[rng() % (sizeof(V) / sizeof(V[0]))]; };

  // 同じ値の再代入、全面消去、片側境界、空区間を明示的に踏む。
  t.set(0, n, 17);
  t.set(0, n, 17);
  t.set(0, n, NONE);
  t.set(0, 0, 1);
  t.set(n, n, 1);
  t.set(0, n, -17);
  t.set(n / 4, (3 * n) / 4, NONE);
  t.set(n / 4, (3 * n) / 4, 0);
  t.get_and_maybe_erase(n / 2, true);
  t.get_and_maybe_erase(n / 2, true);

  // 64-ary FastSet の単語・階層境界で、細かな区間の分割・再結合を確認。
  for (int i : {0, 1, 62, 63, 64, 65, 126, 127, 128, 129, 190, 191, 192, 193,
           254, 255, 256}) {
    if (i < n) t.set(i, i + 1, (i % 2 ? -1 : 1));
  }
  for (int i = 0; i < n; ++i) t.set(i, i + 1, (i % 2 ? 1 : 0));
  t.get_and_maybe_erase(n - 1, true);
  t.get_and_maybe_erase(0, true);
  t.set(0, n, NONE);

  // 乱択の区間代入・極大区間消去・照会を混在させる。
  for (int rep = 0; rep < 850; ++rep) {
    int kind = int(rng() % 12);
    if (kind <= 8) {
      int l = int(rng() % (n + 1));
      int r = int(rng() % (n + 1));
      if (l > r) swap(l, r);
      if (kind == 0) l = 0;
      if (kind == 1) r = n;
      if (kind == 2) r = l;
      t.set(l, r, pick());
    } else {
      const int i = int(rng() % n);
      t.get_and_maybe_erase(i, kind == 9 || kind == 10);
    }
  }
}
}  // namespace

int main() {
  mt19937_64 rng(0x1A7E4A15ULL);
  for (int n : {1, 2, 3, 4, 7, 8, 9, 31, 32, 33, 63, 64, 65, 66, 127, 128, 129,
           191, 192, 193, 255, 256, 257}) {
    run_case(n, rng);
  }
  cerr << "PASS: Intervals_Fast independent array oracle\n";
  return 0;
}
Back to top page