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/dynamic_lazy_persistent_copy_add.test.cpp

Depends on

Code

/*
対象:ds/segtree/dynamic_lazy_segtree.hpp の永続版。
独立オラクル:各操作後の配列をコピーして全バージョンの内容を保存する。任意の過去版からset、multiply、apply、copy_intervalを分岐させる。
コピー元とコピー先が別の根について非零の加算作用を検証し、全区間和と過去版の不変性を照合する。
固定seed 0xDA7AF33、n<=21。自己コピーに非零作用を加えるケースは別の失敗期待テストで扱う。
*/
#include "my_template.hpp"
#include "other/io.hpp"
#include "alg/acted_monoid/sum_add.hpp"
#include "ds/segtree/dynamic_lazy_segtree.hpp"

static mt19937_64 gen(0xDA7AF33ULL);
static int randint(int l, int r) { return uniform_int_distribution<int>(l, r)(gen); }

static void verify(Dynamic_Lazy_SegTree<ActedMonoid_Sum_Add<long long>, true>& seg,
                   Dynamic_Lazy_SegTree<ActedMonoid_Sum_Add<long long>, true>::np root,
                   const vector<long long>& want, int trial, int step, int version) {
  int n = (int)want.size();
  for (int l = 0; l <= n; ++l) {
    long long s = 0;
    for (int r = l; r <= n; ++r) {
      if (r != l) s += want[r-1];
      long long actual = seg.prod(root, l, r);
      if (actual != s) {
        cerr << "dynamic_lazy mismatch trial=" << trial << " step=" << step
             << " version=" << version << " query=[" << l << ',' << r << ")"
             << " actual=" << actual << " expected=" << s << '\n';
        cerr << "array="; for (long long x : want) cerr << x << ',';
        cerr << '\n'; abort();
      }
    }
  }
}

int main() {
  using AM = ActedMonoid_Sum_Add<long long>;
  using Seg = Dynamic_Lazy_SegTree<AM, true>;
  for (int trial = 0; trial < 165; ++trial) {
    int n = randint(1, 21);
    Seg seg(0, n);
    vector<Seg::np> roots = {seg.new_root()};
    vector<vector<long long>> arrays = {vector<long long>(n, 0)};
    for (int step = 0; step < 60; ++step) {
      int i = randint(0, (int)roots.size()-1);
      auto root = roots[i];
      vector<long long> want = arrays[i];
      int op = randint(0, 3);
      int l = randint(0,n), r = randint(0,n);
      if (l > r) swap(l,r);
      if (op == 0) {
        int add = randint(-9,9);
        for (int k=l;k<r;++k) want[k] += add;
        root = seg.apply(root,l,r,add);
      } else if (op == 1) {
        int at = randint(0,n-1), val=randint(-30,30);
        want[at] = val;
        root = seg.set(root,at,val);
      } else if (op == 2) {
        int at = randint(0,n-1), val=randint(-10,10);
        want[at] += val;
        root = seg.multiply(root,at,val);
      } else {
        int j = randint(0,(int)roots.size()-1);
        // Self-copy with nonidentity action is covered by a separate RED test.
        if (roots[j] == root) {
          root=seg.apply(root,l,r,0);
        } else {
          long long add = randint(-7,7);
          for (int k=l;k<r;++k) want[k] = arrays[j][k] + add;
          root = seg.copy_interval(root,roots[j],l,r,add);
        }
      }
      roots.push_back(root);
      arrays.push_back(want);
      verify(seg,root,want,trial,step,(int)roots.size()-1);
      verify(seg,roots[0],arrays[0],trial,step,0);
      for (int rep=0;rep<2;++rep) {
        int v=randint(0,(int)roots.size()-1);
        verify(seg,roots[v],arrays[v],trial,step,v);
      }
    }
  }
  cout << "PASS dynamic_lazy_persistent_copy_add\n";
}
#line 1 "test/5_ai_generated_test/dynamic_lazy_persistent_copy_add.test.cpp"
/*
対象:ds/segtree/dynamic_lazy_segtree.hpp の永続版。
独立オラクル:各操作後の配列をコピーして全バージョンの内容を保存する。任意の過去版からset、multiply、apply、copy_intervalを分岐させる。
コピー元とコピー先が別の根について非零の加算作用を検証し、全区間和と過去版の不変性を照合する。
固定seed 0xDA7AF33、n<=21。自己コピーに非零作用を加えるケースは別の失敗期待テストで扱う。
*/
#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 "alg/acted_monoid/sum_add.hpp"
// Source: https://github.com/maspypy/library/blob/main/alg/acted_monoid/sum_add.hpp
#line 1 "alg/monoid/add.hpp"
// Source: https://github.com/maspypy/library/blob/main/alg/monoid/add.hpp

template <typename E>
struct Monoid_Add {
  using X = E;
  using value_type = X;
  static constexpr X op(const X &x, const X &y) noexcept { return x + y; }
  static constexpr X inverse(const X &x) noexcept { return -x; }
  static constexpr X power(const X &x, ll n) noexcept { return X(n) * x; }
  static constexpr X id() { return X(0); }
  static constexpr bool commute = true;
};
#line 3 "alg/acted_monoid/sum_add.hpp"

template <typename E>
struct ActedMonoid_Sum_Add {
  using Monoid_X = Monoid_Add<E>;
  using Monoid_A = Monoid_Add<E>;
  using X = typename Monoid_X::value_type;
  using A = typename Monoid_A::value_type;
  static constexpr X act(const X &x, const A &a, const ll &size) {
    return x + a * E(size);
  }
};
#line 1 "ds/segtree/dynamic_lazy_segtree.hpp"
// Source: https://github.com/maspypy/library/blob/main/ds/segtree/dynamic_lazy_segtree.hpp
#line 1 "ds/node_pool.hpp"
// Source: https://github.com/maspypy/library/blob/main/ds/node_pool.hpp
// マルチテストケースでも確保済み chunk を再利用する
template <class Node>
struct Node_Pool {
  union Slot {
    Node node;
    Slot* next;

    Slot() {}
    ~Slot() {}
  };
  using np = Node*;

  static constexpr int CHUNK_SIZE = 1 << 12;

  vc<unique_ptr<Slot[]>> chunks;
  int chunk_id = 0;
  int pos = 0;
  Slot* free_head = nullptr;

  ~Node_Pool() {
    auto& cache = chunk_cache();
    for (auto& p : chunks) cache.eb(std::move(p));
  }

  template <class... Args>
  np create(Args&&... args) {
    Slot* s = new_slot();
    return ::new (&s->node) Node(forward<Args>(args)...);
  }

  np clone(const np x) {
    assert(x);
    Slot* s = new_slot();
    return ::new (&s->node) Node(*x);
  }

  void destroy(np x) {
    if (!x) return;
    x->~Node();
    Slot* s = reinterpret_cast<Slot*>(x);
    s->next = free_head;
    free_head = s;
  }

  // 全 node を無効化する。
  // 確保済み chunk は解放せず、次回以降に再利用する。
  void reset() {
    free_head = nullptr;
    chunk_id = 0;
    pos = 0;
  }

  int used() const { return chunk_id * CHUNK_SIZE + pos; }

 private:
  static vc<unique_ptr<Slot[]>>& chunk_cache() {
    // static Node_Pool の destructor より先に破棄されないようにする。
    static auto* cache = new vc<unique_ptr<Slot[]>>();
    return *cache;
  }

  void alloc_chunk() {
    auto& cache = chunk_cache();
    if (cache.empty()) {
      chunks.eb(make_unique<Slot[]>(CHUNK_SIZE));
    } else {
      chunks.eb(std::move(cache.back()));
      cache.pop_back();
    }
  }

  Slot* new_slot() {
    if (free_head) {
      Slot* s = free_head;
      free_head = free_head->next;
      return s;
    }

    if (chunk_id == len(chunks)) alloc_chunk();

    Slot* s = &chunks[chunk_id][pos++];
    if (pos == CHUNK_SIZE) {
      ++chunk_id;
      pos = 0;
    }
    return s;
  }
};
#line 3 "ds/segtree/dynamic_lazy_segtree.hpp"

template <typename AM>
struct Dynamic_Lazy_SegTree_Default_Prod {
  using MX = typename AM::Monoid_X;
  using X = typename AM::X;
  X operator()(ll, ll) const { return MX::id(); }
};

// set, multiply: 2H nodes 程度
// apply: 4H nodes 程度
template <typename ActedMonoid, bool PERSISTENT,
    typename DefaultProd = Dynamic_Lazy_SegTree_Default_Prod<ActedMonoid>>
struct Dynamic_Lazy_SegTree {
  using AM = ActedMonoid;
  using MX = typename AM::Monoid_X;
  using MA = typename AM::Monoid_A;
  using X = typename AM::X;
  using A = typename AM::A;
  using F = DefaultProd;
  F default_prod;

  struct Node {
    Node *l, *r;
    X x;
    A lazy;
  };

  Node_Pool<Node> pool;
  const ll L0, R0;
  using np = Node *;

  Dynamic_Lazy_SegTree(ll L0, ll R0, F default_prod = F{})
      : default_prod(std::move(default_prod)), L0(L0), R0(R0) {}

  np new_root() { return new_node(); }

  np new_node(const X x) {
    np c = pool.create();
    c->l = c->r = nullptr;
    c->x = x, c->lazy = MA::id();
    return c;
  }

  np new_node(ll l, ll r) {
    assert(l < r);
    return new_node(default_prod(l, r));
  }
  np new_node() { return L0 == R0 ? nullptr : new_node(L0, R0); }

  np new_node(const vc<X> &dat) {
    assert(L0 == 0 && R0 == len(dat));
    auto dfs = [&](auto &dfs, ll l, ll r) -> Node * {
      if (l == r) return nullptr;
      if (r - l == 1) return new_node(dat[l]);
      ll m = (l + r) / 2;
      np l_root = dfs(dfs, l, m), r_root = dfs(dfs, m, r);
      X x = MX::op(l_root->x, r_root->x);
      np root = new_node(x);
      root->l = l_root, root->r = r_root;
      return root;
    };
    return dfs(dfs, 0, len(dat));
  }

  X prod(np root, ll l, ll r) {
    if (l == r || !root) return MX::id();
    assert(L0 <= l && l < r && r <= R0);
    X x = MX::id();
    prod_rec(root, L0, R0, l, r, x, MA::id());
    return x;
  }

  X prod_all(np root) { return prod(root, L0, R0); }

  np set(np root, ll i, const X &x) {
    assert(root && L0 <= i && i < R0);
    root = clone(root);
    set_rec(root, L0, R0, i, x);
    return root;
  }

  np multiply(np root, ll i, const X &x) {
    assert(root && L0 <= i && i < R0);
    root = clone(root);
    multiply_rec(root, L0, R0, i, x);
    return root;
  }

  np apply(np root, ll l, ll r, const A &a) {
    if (l == r) return root;
    assert(root && L0 <= l && l < r && r <= R0);
    root = clone(root);
    apply_rec(root, L0, R0, l, r, a);
    return root;
  }

  template <typename F>
  ll max_right(np root, F check, ll L) {
    assert(L0 <= L && L <= R0 && check(MX::id()));
    if (L == R0) return R0;
    assert(root);
    X x = MX::id();
    return max_right_rec(root, check, L0, R0, L, x, MA::id());
  }

  template <typename F>
  ll min_left(np root, F check, ll R) {
    assert(L0 <= R && R <= R0 && check(MX::id()));
    if (R == L0) return L0;
    assert(root);
    X x = MX::id();
    return min_left_rec(root, check, L0, R0, R, x, MA::id());
  }

  // 生成済みの葉について f(idx, val, end) を呼ぶ
  template <typename F>
  void enumerate(np root, F f) {
    bool end = false;
    auto dfs = [&](auto &dfs, np c, ll l, ll r, A a) -> void {
      if (!c) return;
      if (r - l == 1) {
        f(l, AM::act(c->x, a, 1), end);
        return;
      }
      ll m = (l + r) / 2;
      a = MA::op(c->lazy, a);
      dfs(dfs, c->l, l, m, a);
      if (end) return;
      dfs(dfs, c->r, m, r, a);
      if (end) return;
    };
    dfs(dfs, root, L0, R0, MA::id());
  }

  void reset() { pool.reset(); }

  // root[l:r) を apply(other[l:r),a) で上書きしたものを返す
  np copy_interval(np root, np other, ll l, ll r, A a) {
    static_assert(PERSISTENT);
    assert(L0 <= l && l <= r && r <= R0);
    if (l == r) return root;
    assert(root);
    if (root == other) return apply(root, l, r, a);
    root = clone(root);
    copy_interval_rec(root, other, L0, R0, l, r, a);
    return root;
  }

 private:
  np clone(np c) {
    if (!c || !PERSISTENT) return c;
    return pool.clone(c);
  }

  np own(np c, ll l, ll r) { return c ? clone(c) : new_node(l, r); }

  X value(np c, ll l, ll r) { return c ? c->x : default_prod(l, r); }

  void tag(np c, const A &a, ll len) {
    c->x = AM::act(c->x, a, len);
    c->lazy = MA::op(c->lazy, a);
  }

  // c は書き換え可能。左右の子も書き換え可能になったかを返す
  bool push(np c, ll l, ll m, ll r) {
    assert(r - l >= 2);
    if (c->lazy == MA::id()) return false;
    c->l = own(c->l, l, m);
    c->r = own(c->r, m, r);
    tag(c->l, c->lazy, m - l);
    tag(c->r, c->lazy, r - m);
    c->lazy = MA::id();
    return true;
  }

  void pull(np c, ll l, ll m, ll r) {
    c->x = MX::op(value(c->l, l, m), value(c->r, m, r));
  }

  void copy_interval_rec(np c, np d, ll l, ll r, ll ql, ll qr, A a) {
    // c[ql,qr) <- apply(d[ql,qr),a)
    // c はすでに新しくしてある
    if (ql <= l && r <= qr) {
      if (d) {
        c->x = d->x;
        c->lazy = d->lazy;
        c->l = d->l, c->r = d->r;
      } else {
        c->x = default_prod(l, r);
        c->lazy = MA::id();
        c->l = c->r = nullptr;
      }
      tag(c, a, r - l);
      return;
    }
    ll m = (l + r) / 2;
    bool pushed = push(c, l, m, r);
    if (d) a = MA::op(d->lazy, a);
    if (ql < m) {
      if (!pushed) c->l = own(c->l, l, m);
      copy_interval_rec(c->l, d ? d->l : nullptr, l, m, ql, qr, a);
    }
    if (m < qr) {
      if (!pushed) c->r = own(c->r, m, r);
      copy_interval_rec(c->r, d ? d->r : nullptr, m, r, ql, qr, a);
    }
    pull(c, l, m, r);
  }

  // c はすでに新しくしてある
  void set_rec(np c, ll l, ll r, ll i, const X &x) {
    if (r - l == 1) {
      c->x = x;
      c->lazy = MA::id();
      return;
    }
    ll m = (l + r) / 2;
    bool pushed = push(c, l, m, r);
    if (i < m) {
      if (!pushed) c->l = own(c->l, l, m);
      set_rec(c->l, l, m, i, x);
    } else {
      if (!pushed) c->r = own(c->r, m, r);
      set_rec(c->r, m, r, i, x);
    }
    pull(c, l, m, r);
  }

  void multiply_rec(np c, ll l, ll r, ll i, const X &x) {
    if (r - l == 1) {
      c->x = MX::op(c->x, x);
      c->lazy = MA::id();
      return;
    }
    ll m = (l + r) / 2;
    bool pushed = push(c, l, m, r);
    if (i < m) {
      if (!pushed) c->l = own(c->l, l, m);
      multiply_rec(c->l, l, m, i, x);
    } else {
      if (!pushed) c->r = own(c->r, m, r);
      multiply_rec(c->r, m, r, i, x);
    }
    pull(c, l, m, r);
  }

  void apply_rec(np c, ll l, ll r, ll ql, ll qr, const A &a) {
    if (ql <= l && r <= qr) {
      tag(c, a, r - l);
      return;
    }
    ll m = (l + r) / 2;
    bool pushed = push(c, l, m, r);
    if (ql < m) {
      if (!pushed) c->l = own(c->l, l, m);
      apply_rec(c->l, l, m, ql, qr, a);
    }
    if (m < qr) {
      if (!pushed) c->r = own(c->r, m, r);
      apply_rec(c->r, m, r, ql, qr, a);
    }
    pull(c, l, m, r);
  }

  void prod_rec(np c, ll l, ll r, ll ql, ll qr, X &x, A a) {
    if (!c) {
      ll L = max(l, ql), R = min(r, qr);
      x = MX::op(x, AM::act(default_prod(L, R), a, R - L));
      return;
    }
    if (ql <= l && r <= qr) {
      x = MX::op(x, AM::act(c->x, a, r - l));
      return;
    }
    ll m = (l + r) / 2;
    a = MA::op(c->lazy, a);
    if (ql < m) prod_rec(c->l, l, m, ql, qr, x, a);
    if (m < qr) prod_rec(c->r, m, r, ql, qr, x, a);
  }

  template <typename F>
  ll max_right_rec(np c, const F &check, ll l, ll r, ll ql, X &x, A a) {
    if (r <= ql) return r;
    if (ql <= l) {
      X y = MX::op(x, AM::act(value(c, l, r), a, r - l));
      if (check(y)) {
        x = y;
        return r;
      }
    }
    if (r - l == 1) return l;
    ll m = (l + r) / 2;
    if (c) a = MA::op(c->lazy, a);
    if (ql < m) {
      ll k = max_right_rec(c ? c->l : nullptr, check, l, m, ql, x, a);
      if (k < m) return k;
    }
    return max_right_rec(c ? c->r : nullptr, check, m, r, ql, x, a);
  }

  template <typename F>
  ll min_left_rec(np c, const F &check, ll l, ll r, ll qr, X &x, A a) {
    if (qr <= l) return l;
    if (r <= qr) {
      X y = MX::op(AM::act(value(c, l, r), a, r - l), x);
      if (check(y)) {
        x = y;
        return l;
      }
    }
    if (r - l == 1) return r;
    ll m = (l + r) / 2;
    if (c) a = MA::op(c->lazy, a);
    if (m < qr) {
      ll k = min_left_rec(c ? c->r : nullptr, check, m, r, qr, x, a);
      if (m < k) return k;
    }
    return min_left_rec(c ? c->l : nullptr, check, l, m, qr, x, a);
  }
};
#line 11 "test/5_ai_generated_test/dynamic_lazy_persistent_copy_add.test.cpp"

static mt19937_64 gen(0xDA7AF33ULL);
static int randint(int l, int r) { return uniform_int_distribution<int>(l, r)(gen); }

static void verify(Dynamic_Lazy_SegTree<ActedMonoid_Sum_Add<long long>, true>& seg,
                   Dynamic_Lazy_SegTree<ActedMonoid_Sum_Add<long long>, true>::np root,
                   const vector<long long>& want, int trial, int step, int version) {
  int n = (int)want.size();
  for (int l = 0; l <= n; ++l) {
    long long s = 0;
    for (int r = l; r <= n; ++r) {
      if (r != l) s += want[r-1];
      long long actual = seg.prod(root, l, r);
      if (actual != s) {
        cerr << "dynamic_lazy mismatch trial=" << trial << " step=" << step
             << " version=" << version << " query=[" << l << ',' << r << ")"
             << " actual=" << actual << " expected=" << s << '\n';
        cerr << "array="; for (long long x : want) cerr << x << ',';
        cerr << '\n'; abort();
      }
    }
  }
}

int main() {
  using AM = ActedMonoid_Sum_Add<long long>;
  using Seg = Dynamic_Lazy_SegTree<AM, true>;
  for (int trial = 0; trial < 165; ++trial) {
    int n = randint(1, 21);
    Seg seg(0, n);
    vector<Seg::np> roots = {seg.new_root()};
    vector<vector<long long>> arrays = {vector<long long>(n, 0)};
    for (int step = 0; step < 60; ++step) {
      int i = randint(0, (int)roots.size()-1);
      auto root = roots[i];
      vector<long long> want = arrays[i];
      int op = randint(0, 3);
      int l = randint(0,n), r = randint(0,n);
      if (l > r) swap(l,r);
      if (op == 0) {
        int add = randint(-9,9);
        for (int k=l;k<r;++k) want[k] += add;
        root = seg.apply(root,l,r,add);
      } else if (op == 1) {
        int at = randint(0,n-1), val=randint(-30,30);
        want[at] = val;
        root = seg.set(root,at,val);
      } else if (op == 2) {
        int at = randint(0,n-1), val=randint(-10,10);
        want[at] += val;
        root = seg.multiply(root,at,val);
      } else {
        int j = randint(0,(int)roots.size()-1);
        // Self-copy with nonidentity action is covered by a separate RED test.
        if (roots[j] == root) {
          root=seg.apply(root,l,r,0);
        } else {
          long long add = randint(-7,7);
          for (int k=l;k<r;++k) want[k] = arrays[j][k] + add;
          root = seg.copy_interval(root,roots[j],l,r,add);
        }
      }
      roots.push_back(root);
      arrays.push_back(want);
      verify(seg,root,want,trial,step,(int)roots.size()-1);
      verify(seg,roots[0],arrays[0],trial,step,0);
      for (int rep=0;rep<2;++rep) {
        int v=randint(0,(int)roots.size()-1);
        verify(seg,roots[v],arrays[v],trial,step,v);
      }
    }
  }
  cout << "PASS dynamic_lazy_persistent_copy_add\n";
}
Back to top page