library

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

View the Project on GitHub maspypy/library

:warning: graph/ds/tree_wavelet_matrix.hpp

Depends on

Code

#include "ds/wavelet_matrix/wavelet_matrix.hpp"
#include "graph/tree.hpp"

// https://atcoder.jp/contests/pakencamp-2022-day1/tasks/pakencamp_2022_day1_j
// https://atcoder.jp/contests/utpc2011/tasks/utpc2011_12
template <typename TREE, bool edge, typename T, bool COMPRESS,
          typename Monoid = Monoid_Add<T>>
struct Tree_Wavelet_Matrix {
  TREE& tree;
  int N;
  using WM = Wavelet_Matrix<T, COMPRESS, Monoid_Add<T>>;
  using X = typename Monoid::value_type;
  WM wm;

  Tree_Wavelet_Matrix(TREE& tree, vc<T> A, vc<X> SUM_data = {}, int log = -1)
      : tree(tree), N(tree.N) {
    vc<X>& S = SUM_data;
    vc<T> A1;
    vc<X> S1;
    A1.resize(N);
    if (!S.empty()) S1.resize(N);
    if (!edge) {
      assert(len(A) == N && (len(S) == 0 || len(S) == N));
      FOR(v, N) A1[tree.LID[v]] = A[v];
      if (len(S) == N) { FOR(v, N) S1[tree.LID[v]] = S[v]; }
      wm.build(A1, S1, log);
    } else {
      assert(len(A) == N - 1 && (len(S) == 0 || len(S) == N - 1));
      if (!S.empty()) {
        FOR(e, N - 1) { S1[tree.LID[tree.e_to_v(e)]] = S[e]; }
      }
      FOR(e, N - 1) { A1[tree.LID[tree.e_to_v(e)]] = A[e]; }
      wm.build(A1, S1, log);
    }
  }

  // xor した結果で [a, b) に収まるものを数える
  int count_path(int s, int t, T a, T b, T xor_val = 0) {
    return wm.count(get_segments(s, t), a, b, xor_val);
  }

  // xor した結果で [a, b) に収まるものを数える
  int count_subtree(int u, T a, T b, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.count(l + edge, r, a, b, xor_val);
  }

  // xor した結果で、[L, R) の中で k>=0 番目と prefix sum
  pair<T, X> kth_value_and_sum_path(int s, int t, int k, T xor_val = 0) {
    return wm.kth_value_and_sum(get_segments(s, t), k, xor_val);
  }

  // xor した結果で、[L, R) の中で k>=0 番目と prefix sum
  pair<T, X> kth_value_and_sum_subtree(int u, int k, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.kth_value_and_sum(l + edge, r, k, xor_val);
  }

  // xor した結果で、[L, R) の中で k>=0 番目
  T kth_path(int s, int t, int k, T xor_val = 0) {
    return wm.kth(get_segments(s, t), k, xor_val);
  }

  // xor した結果で、[L, R) の中で k>=0 番目
  T kth_subtree(int u, int k, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.kth(l + edge, r, k, xor_val);
  }

  // xor した結果で、[L, R) の中で中央値。
  // LOWER = true:下側中央値、false:上側中央値
  T median_path(bool UPPER, int s, int t, T xor_val = 0) {
    return wm.median(UPPER, get_segments(s, t), xor_val);
  }

  T median_subtree(bool UPPER, int u, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.median(UPPER, l + edge, r, xor_val);
  }

  // xor した結果で [k1, k2) 番目であるところの SUM_data の和
  X sum_path(int s, int t, int k1, int k2, T xor_val = 0) {
    return wm.sum(get_segments(s, t), k1, k2, xor_val);
  }

  // xor した結果で [k1, k2) 番目であるところの SUM_data の和
  X sum_subtree(int u, int k1, int k2, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.sum(l + edge, r, k1, k2, xor_val);
  }

  X sum_all_path(int s, int t) { return wm.sum_all(get_segments(s, t)); }

  X sum_all_subtree(int u) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.sum_all(l + edge, r);
  }

private:
  vc<pair<int, int>> get_segments(int s, int t) {
    vc<pair<int, int>> segments = tree.get_path_decomposition(s, t, edge);
    for (auto&& [a, b]: segments) {
      if (a >= b) swap(a, b);
      ++b;
    }
    return segments;
  }
};
#line 1 "graph/ds/tree_wavelet_matrix.hpp"

#line 1 "ds/bit_vector.hpp"
struct Bit_Vector {
  vc<pair<u32, u32>> dat;
  Bit_Vector(int n) { dat.assign((n + 63) >> 5, {0, 0}); }

  void set(int i) { dat[i >> 5].fi |= u32(1) << (i & 31); }

  void build() {
    FOR(i, len(dat) - 1) dat[i + 1].se = dat[i].se + popcnt(dat[i].fi);
  }

  // [0, k) 内の 1 の個数
  int rank(int k, bool f = 1) {
    auto [a, b] = dat[k >> 5];
    int ret = b + popcnt(a & ((u32(1) << (k & 31)) - 1));
    return (f ? ret : k - ret);
  }
};
#line 2 "ds/wavelet_matrix/wavelet_matrix.hpp"

// 座圧するかどうかを COMPRESS で指定する

// xor 的な使い方をする場合には、コンストラクタで log を渡すこと

template <typename T, bool COMPRESS, bool USE_SUM>
struct Wavelet_Matrix {
  static_assert(is_same_v<T, int> || is_same_v<T, ll>);
  int N, lg;
  vector<int> mid;
  vector<Bit_Vector> bv;
  vc<T> key;
  bool set_log;
  vvc<T> cumsum;

  Wavelet_Matrix() {}

  // 和を使わないなら、SUM_data は空でよい

  Wavelet_Matrix(vc<T> A, vc<T> SUM_data = {}, int log = -1) {
    build(A, SUM_data, log);
  }

  void build(vc<T> A, vc<T> SUM_data = {}, int log = -1) {
    if constexpr (USE_SUM) { assert(len(SUM_data) == len(A)); }
    N = len(A), lg = log, set_log = (log != -1);
    if (N == 0) {
      lg = 0;
      cumsum.resize(1);
      cumsum[0] = {0};
      return;
    }
    vc<T>& S = SUM_data;
    if (COMPRESS) {
      assert(!set_log);
      key.reserve(N);
      vc<int> I = argsort(A);
      for (auto&& i: I) {
        if (key.empty() || key.back() != A[i]) key.eb(A[i]);
        A[i] = len(key) - 1;
      }
      key.shrink_to_fit();
    }
    if (lg == -1) lg = __lg(max<ll>(MAX(A), 1)) + 1;
    mid.resize(lg), bv.assign(lg, Bit_Vector(N));
    if constexpr (USE_SUM) cumsum.assign(1 + lg, vc<T>(N + 1, 0));
    S.resize(N);
    vc<T> A0(N), A1(N);
    vc<T> S0(N), S1(N);
    FOR_R(d, -1, lg) {
      int p0 = 0, p1 = 0;
      if constexpr (USE_SUM) {
        FOR(i, N) { cumsum[d + 1][i + 1] = cumsum[d + 1][i] + S[i]; }
      }
      if (d == -1) break;
      FOR(i, N) {
        bool f = (A[i] >> d & 1);
        if (!f) {
          if constexpr (USE_SUM) S0[p0] = S[i];
          A0[p0++] = A[i];
        } else {
          if constexpr (USE_SUM) S1[p1] = S[i];
          bv[d].set(i), A1[p1++] = A[i];
        }
      }
      mid[d] = p0;
      bv[d].build();
      swap(A, A0), swap(S, S0);
      FOR(i, p1) A[p0 + i] = A1[i], S[p0 + i] = S1[i];
    }
  }

  // [L,R) x [a,b), (cnt, monoid value)

  pair<int, T> range_cnt_sum(int L, int R, T a, T b, T xor_val = 0) {
    if (xor_val != 0) assert(set_log);
    if (a == b) return {0, 0};
    if (COMPRESS) a = LB(key, a), b = LB(key, b);
    int cnt = 0;
    T sm = 0;
    auto dfs = [&](auto& dfs, int d, int L, int R, T lx, T rx) -> void {
      if (rx <= a || b <= lx) return;
      if (a <= lx && rx <= b) {
        cnt += R - L, sm += get(d, L, R);
        return;
      }
      --d;
      T mx = (lx + rx) / 2;
      int l0 = bv[d].rank(L, 0), r0 = bv[d].rank(R, 0);
      int l1 = L + mid[d] - l0, r1 = R + mid[d] - r0;
      if (xor_val >> d & 1) swap(l0, l1), swap(r0, r1);
      dfs(dfs, d, l0, r0, lx, mx), dfs(dfs, d, l1, r1, mx, rx);
    };
    dfs(dfs, lg, L, R, 0, T(1) << lg);
    return {cnt, sm};
  }

  // smallest k, sum of [0,k)

  pair<T, T> kth_value_sum(int L, int R, int k, T xor_val = 0) {
    assert(0 <= k && k <= R - L);
    if (k == R - L) { return {infty<T>, sum_all(L, R)}; }
    if (L == R) return {infty<T>, 0};
    if (xor_val != 0) assert(set_log);
    T sm = 0, val = 0;
    for (int d = lg - 1; d >= 0; --d) {
      // いま幅 d+1 の trie node に居て, 幅 d のところに行く

      int l0 = bv[d].rank(L, 0), r0 = bv[d].rank(R, 0);
      int l1 = L + mid[d] - l0, r1 = R + mid[d] - r0;
      if (xor_val >> d & 1) swap(l0, l1), swap(r0, r1);
      if (k < r0 - l0) {
        L = l0, R = r0;
      } else {
        k -= r0 - l0, val |= T(1) << d, L = l1, R = r1;
        if constexpr (USE_SUM) sm += get(d, l0, r0);
      }
    }
    if constexpr (USE_SUM) sm += get(0, L, L + k);
    if (COMPRESS) val = key[val];

    return {val, sm};
  }

  int count(int L, int R, T a, T b, T xor_val = 0) {
    return range_cnt_sum(L, R, a, b, xor_val).fi;
  }
  T sum(int L, int R, T a, T b, T xor_val = 0) {
    static_assert(USE_SUM);
    return range_cnt_sum(L, R, a, b, xor_val).se;
  }

  T sum_index_range(int L, int R, int k1, int k2, T xor_val = 0) {
    static_assert(USE_SUM);
    return kth_value_sum(L, R, k2, xor_val).se
           - kth_value_sum(L, R, k1, xor_val).se;
  }
  T kth(int L, int R, int k, T xor_val = 0) {
    assert(0 <= k && k < R - L);
    return kth_value_sum(L, R, k, xor_val).fi;
  }

  // x 以上最小 OR infty<T>

  T next(int L, int R, T x, T xor_val = 0) {
    if (xor_val != 0) assert(set_log);
    if (L == R) return infty<T>;
    if (COMPRESS) x = LB(key, x);
    T ans = infty<T>;

    auto dfs = [&](auto& dfs, int d, int L, int R, T lx, T rx) -> void {
      if (ans <= lx || L == R || rx <= x) return;
      if (d == 0) {
        chmin(ans, lx);
        return;
      }
      --d;
      T mx = (lx + rx) / 2;
      int l0 = bv[d].rank(L, 0), r0 = bv[d].rank(R, 0);
      int l1 = L + mid[d] - l0, r1 = R + mid[d] - r0;
      if (xor_val >> d & 1) swap(l0, l1), swap(r0, r1);
      dfs(dfs, d, l0, r0, lx, mx), dfs(dfs, d, l1, r1, mx, rx);
    };
    dfs(dfs, lg, L, R, 0, T(1) << lg);
    if (COMPRESS && ans < infty<T>) ans = key[ans];
    return ans;
  }

  // x 以下最大 OR -infty<T>

  T prev(int L, int R, T x, T xor_val = 0) {
    if (xor_val != 0) assert(set_log);
    if (L == R) return -infty<T>;
    T ans = -infty<int>;
    ++x;
    if (COMPRESS) x = LB(key, x);

    auto dfs = [&](auto& dfs, int d, int L, int R, T lx, T rx) -> void {
      if ((rx - 1) <= ans || L == R || x <= lx) return;
      if (d == 0) {
        chmax(ans, lx);
        return;
      }
      --d;
      T mx = (lx + rx) / 2;
      int l0 = bv[d].rank(L, 0), r0 = bv[d].rank(R, 0);
      int l1 = L + mid[d] - l0, r1 = R + mid[d] - r0;
      if (xor_val >> d & 1) swap(l0, l1), swap(r0, r1);
      dfs(dfs, d, l1, r1, mx, rx), dfs(dfs, d, l0, r0, lx, mx);
    };
    dfs(dfs, lg, L, R, 0, T(1) << lg);
    if (COMPRESS && ans != -infty<T>) ans = key[ans];
    return ans;
  }

  // xor した結果で、[L, R) の中で中央値。

  // LOWER = true:下側中央値、false:上側中央値

  T median(bool UPPER, int L, int R, T xor_val = 0) {
    int n = R - L;
    int k = (UPPER ? n / 2 : (n - 1) / 2);
    return kth(L, R, k, xor_val);
  }

  T sum_all(int L, int R) { return get(lg, L, R); }

  // check(cnt, prefix sum) が true となるような最大の (cnt, sum)

  template <typename F>
  pair<int, T> max_right(F check, int L, int R, T xor_val = 0) {
    assert(check(0, 0));
    if (xor_val != 0) assert(set_log);
    if (L == R) return {0, 0};
    if (check(R - L, get(lg, L, R))) return {R - L, get(lg, L, R)};
    int cnt = 0;
    T sm = 0;
    for (int d = lg - 1; d >= 0; --d) {
      int l0 = bv[d].rank(L, 0), r0 = bv[d].rank(R, 0);
      int l1 = L + mid[d] - l0, r1 = R + mid[d] - r0;
      if (xor_val >> d & 1) swap(l0, l1), swap(r0, r1);
      if (check(cnt + r0 - l0, sm + get(d, l0, r0))) {
        cnt += r0 - l0, sm += get(d, l0, r0);
        L = l1, R = r1;
      } else {
        L = l0, R = r0;
      }
    }
    int k = binary_search(
        [&](int k) -> bool { return check(cnt + k, sm + get(0, L, L + k)); }, 0,
        R - L);
    cnt += k, sm += get(0, L, L + k);
    return {cnt, sm};
  }

private:
  inline T get(int d, int L, int R) {
    if constexpr (USE_SUM) return cumsum[d][R] - cumsum[d][L];
    return 0;
  }
};
#line 2 "graph/tree.hpp"

#line 2 "graph/base.hpp"

template <typename T>
struct Edge {
  int frm, to;
  T cost;
  int id;
};

template <typename T = int, bool directed = false>
struct Graph {
  static constexpr bool is_directed = directed;
  int N, M;
  using cost_type = T;
  using edge_type = Edge<T>;
  vector<edge_type> edges;
  vector<int> indptr;
  vector<edge_type> csr_edges;
  vc<int> vc_deg, vc_indeg, vc_outdeg;
  bool prepared;

  class OutgoingEdges {
  public:
    OutgoingEdges(const Graph* G, int l, int r) : G(G), l(l), r(r) {}

    const edge_type* begin() const {
      if (l == r) { return 0; }
      return &G->csr_edges[l];
    }

    const edge_type* end() const {
      if (l == r) { return 0; }
      return &G->csr_edges[r];
    }

  private:
    const Graph* G;
    int l, r;
  };

  bool is_prepared() { return prepared; }

  Graph() : N(0), M(0), prepared(0) {}
  Graph(int N) : N(N), M(0), prepared(0) {}

  void build(int n) {
    N = n, M = 0;
    prepared = 0;
    edges.clear();
    indptr.clear();
    csr_edges.clear();
    vc_deg.clear();
    vc_indeg.clear();
    vc_outdeg.clear();
  }

  void add(int frm, int to, T cost = 1, int i = -1) {
    assert(!prepared);
    assert(0 <= frm && 0 <= to && to < N);
    if (i == -1) i = M;
    auto e = edge_type({frm, to, cost, i});
    edges.eb(e);
    ++M;
  }

#ifdef FASTIO
  // wt, off
  void read_tree(bool wt = false, int off = 1) { read_graph(N - 1, wt, off); }

  void read_graph(int M, bool wt = false, int off = 1) {
    for (int m = 0; m < M; ++m) {
      INT(a, b);
      a -= off, b -= off;
      if (!wt) {
        add(a, b);
      } else {
        T c;
        read(c);
        add(a, b, c);
      }
    }
    build();
  }
#endif

  void build() {
    assert(!prepared);
    prepared = true;
    indptr.assign(N + 1, 0);
    for (auto&& e: edges) {
      indptr[e.frm + 1]++;
      if (!directed) indptr[e.to + 1]++;
    }
    for (int v = 0; v < N; ++v) { indptr[v + 1] += indptr[v]; }
    auto counter = indptr;
    csr_edges.resize(indptr.back() + 1);
    for (auto&& e: edges) {
      csr_edges[counter[e.frm]++] = e;
      if (!directed)
        csr_edges[counter[e.to]++] = edge_type({e.to, e.frm, e.cost, e.id});
    }
  }

  OutgoingEdges operator[](int v) const {
    assert(prepared);
    return {this, indptr[v], indptr[v + 1]};
  }

  vc<int> deg_array() {
    if (vc_deg.empty()) calc_deg();
    return vc_deg;
  }

  pair<vc<int>, vc<int>> deg_array_inout() {
    if (vc_indeg.empty()) calc_deg_inout();
    return {vc_indeg, vc_outdeg};
  }

  int deg(int v) {
    if (vc_deg.empty()) calc_deg();
    return vc_deg[v];
  }

  int in_deg(int v) {
    if (vc_indeg.empty()) calc_deg_inout();
    return vc_indeg[v];
  }

  int out_deg(int v) {
    if (vc_outdeg.empty()) calc_deg_inout();
    return vc_outdeg[v];
  }

#ifdef FASTIO
  void debug() {
    print("Graph");
    if (!prepared) {
      print("frm to cost id");
      for (auto&& e: edges) print(e.frm, e.to, e.cost, e.id);
    } else {
      print("indptr", indptr);
      print("frm to cost id");
      FOR(v, N) for (auto&& e: (*this)[v]) print(e.frm, e.to, e.cost, e.id);
    }
  }
#endif

  vc<int> new_idx;
  vc<bool> used_e;

  // G における頂点 V[i] が、新しいグラフで i になるようにする
  // {G, es}
  // sum(deg(v)) の計算量になっていて、
  // 新しいグラフの n+m より大きい可能性があるので注意
  Graph<T, directed> rearrange(vc<int> V, bool keep_eid = 0) {
    if (len(new_idx) != N) new_idx.assign(N, -1);
    int n = len(V);
    FOR(i, n) new_idx[V[i]] = i;
    Graph<T, directed> G(n);
    vc<int> history;
    FOR(i, n) {
      for (auto&& e: (*this)[V[i]]) {
        if (len(used_e) <= e.id) used_e.resize(e.id + 1);
        if (used_e[e.id]) continue;
        int a = e.frm, b = e.to;
        if (new_idx[a] != -1 && new_idx[b] != -1) {
          history.eb(e.id);
          used_e[e.id] = 1;
          int eid = (keep_eid ? e.id : -1);
          G.add(new_idx[a], new_idx[b], e.cost, eid);
        }
      }
    }
    FOR(i, n) new_idx[V[i]] = -1;
    for (auto&& eid: history) used_e[eid] = 0;
    G.build();
    return G;
  }

  Graph<T, true> to_directed_tree(int root = -1) {
    if (root == -1) root = 0;
    assert(!is_directed && prepared && M == N - 1);
    Graph<T, true> G1(N);
    vc<int> par(N, -1);
    auto dfs = [&](auto& dfs, int v) -> void {
      for (auto& e: (*this)[v]) {
        if (e.to == par[v]) continue;
        par[e.to] = v, dfs(dfs, e.to);
      }
    };
    dfs(dfs, root);
    for (auto& e: edges) {
      int a = e.frm, b = e.to;
      if (par[a] == b) swap(a, b);
      assert(par[b] == a);
      G1.add(a, b, e.cost);
    }
    G1.build();
    return G1;
  }

private:
  void calc_deg() {
    assert(vc_deg.empty());
    vc_deg.resize(N);
    for (auto&& e: edges) vc_deg[e.frm]++, vc_deg[e.to]++;
  }

  void calc_deg_inout() {
    assert(vc_indeg.empty());
    vc_indeg.resize(N);
    vc_outdeg.resize(N);
    for (auto&& e: edges) { vc_indeg[e.to]++, vc_outdeg[e.frm]++; }
  }
};
#line 4 "graph/tree.hpp"

// HLD euler tour をとっていろいろ。

template <typename GT>
struct Tree {
  using Graph_type = GT;
  GT &G;
  using WT = typename GT::cost_type;
  int N;
  vector<int> LID, RID, head, V, parent, VtoE;
  vc<int> depth;
  vc<WT> depth_weighted;

  Tree(GT &G, int r = 0, bool hld = 1) : G(G) { build(r, hld); }

  void build(int r = 0, bool hld = 1) {
    if (r == -1) return; // build を遅延したいとき

    N = G.N;
    LID.assign(N, -1), RID.assign(N, -1), head.assign(N, r);
    V.assign(N, -1), parent.assign(N, -1), VtoE.assign(N, -1);
    depth.assign(N, -1), depth_weighted.assign(N, 0);
    assert(G.is_prepared());
    int t1 = 0;
    dfs_sz(r, -1, hld);
    dfs_hld(r, t1);
  }

  void dfs_sz(int v, int p, bool hld) {
    auto &sz = RID;
    parent[v] = p;
    depth[v] = (p == -1 ? 0 : depth[p] + 1);
    sz[v] = 1;
    int l = G.indptr[v], r = G.indptr[v + 1];
    auto &csr = G.csr_edges;
    // 使う辺があれば先頭にする

    for (int i = r - 2; i >= l; --i) {
      if (hld && depth[csr[i + 1].to] == -1) swap(csr[i], csr[i + 1]);
    }
    int hld_sz = 0;
    for (int i = l; i < r; ++i) {
      auto e = csr[i];
      if (depth[e.to] != -1) continue;
      depth_weighted[e.to] = depth_weighted[v] + e.cost;
      VtoE[e.to] = e.id;
      dfs_sz(e.to, v, hld);
      sz[v] += sz[e.to];
      if (hld && chmax(hld_sz, sz[e.to]) && l < i) { swap(csr[l], csr[i]); }
    }
  }

  void dfs_hld(int v, int &times) {
    LID[v] = times++;
    RID[v] += LID[v];
    V[LID[v]] = v;
    bool heavy = true;
    for (auto &&e: G[v]) {
      if (depth[e.to] <= depth[v]) continue;
      head[e.to] = (heavy ? head[v] : e.to);
      heavy = false;
      dfs_hld(e.to, times);
    }
  }

  vc<int> heavy_path_at(int v) {
    vc<int> P = {v};
    while (1) {
      int a = P.back();
      for (auto &&e: G[a]) {
        if (e.to != parent[a] && head[e.to] == v) {
          P.eb(e.to);
          break;
        }
      }
      if (P.back() == a) break;
    }
    return P;
  }

  int heavy_child(int v) {
    int k = LID[v] + 1;
    if (k == N) return -1;
    int w = V[k];
    return (parent[w] == v ? w : -1);
  }

  int e_to_v(int eid) {
    auto e = G.edges[eid];
    return (parent[e.frm] == e.to ? e.frm : e.to);
  }
  int v_to_e(int v) { return VtoE[v]; }
  int get_eid(int u, int v) {
    if (parent[u] != v) swap(u, v);
    assert(parent[u] == v);
    return VtoE[u];
  }

  int ELID(int v) { return 2 * LID[v] - depth[v]; }
  int ERID(int v) { return 2 * RID[v] - depth[v] - 1; }

  // 目標地点へ進む個数が k

  int LA(int v, int k) {
    assert(k <= depth[v]);
    while (1) {
      int u = head[v];
      if (LID[v] - k >= LID[u]) return V[LID[v] - k];
      k -= LID[v] - LID[u] + 1;
      v = parent[u];
    }
  }
  int la(int u, int v) { return LA(u, v); }

  int LCA(int u, int v) {
    for (;; v = parent[head[v]]) {
      if (LID[u] > LID[v]) swap(u, v);
      if (head[u] == head[v]) return u;
    }
  }

  int meet(int a, int b, int c) { return LCA(a, b) ^ LCA(a, c) ^ LCA(b, c); }
  int lca(int u, int v) { return LCA(u, v); }

  int subtree_size(int v, int root = -1) {
    if (root == -1) return RID[v] - LID[v];
    if (v == root) return N;
    int x = jump(v, root, 1);
    if (in_subtree(v, x)) return RID[v] - LID[v];
    return N - RID[x] + LID[x];
  }

  int dist(int a, int b) {
    int c = LCA(a, b);
    return depth[a] + depth[b] - 2 * depth[c];
  }

  WT dist_weighted(int a, int b) {
    int c = LCA(a, b);
    return depth_weighted[a] + depth_weighted[b] - WT(2) * depth_weighted[c];
  }

  // a is in b

  bool in_subtree(int a, int b) { return LID[b] <= LID[a] && LID[a] < RID[b]; }

  int jump(int a, int b, ll k) {
    if (k == 1) {
      if (a == b) return -1;
      return (in_subtree(b, a) ? LA(b, depth[b] - depth[a] - 1) : parent[a]);
    }
    int c = LCA(a, b);
    int d_ac = depth[a] - depth[c];
    int d_bc = depth[b] - depth[c];
    if (k > d_ac + d_bc) return -1;
    if (k <= d_ac) return LA(a, k);
    return LA(b, d_ac + d_bc - k);
  }

  vc<int> collect_child(int v) {
    vc<int> res;
    for (auto &&e: G[v])
      if (e.to != parent[v]) res.eb(e.to);
    return res;
  }

  vc<int> collect_light(int v) {
    vc<int> res;
    bool skip = true;
    for (auto &&e: G[v])
      if (e.to != parent[v]) {
        if (!skip) res.eb(e.to);
        skip = false;
      }
    return res;
  }

  vc<pair<int, int>> get_path_decomposition(int u, int v, bool edge) {
    // [始点, 終点] の"閉"区間列。

    vc<pair<int, int>> up, down;
    while (1) {
      if (head[u] == head[v]) break;
      if (LID[u] < LID[v]) {
        down.eb(LID[head[v]], LID[v]);
        v = parent[head[v]];
      } else {
        up.eb(LID[u], LID[head[u]]);
        u = parent[head[u]];
      }
    }
    if (LID[u] < LID[v]) down.eb(LID[u] + edge, LID[v]);
    elif (LID[v] + edge <= LID[u]) up.eb(LID[u], LID[v] + edge);
    reverse(all(down));
    up.insert(up.end(), all(down));
    return up;
  }

  vc<int> restore_path(int u, int v) {
    vc<int> P;
    for (auto &&[a, b]: get_path_decomposition(u, v, 0)) {
      if (a <= b) {
        FOR(i, a, b + 1) P.eb(V[i]);
      } else {
        FOR_R(i, b, a + 1) P.eb(V[i]);
      }
    }
    return P;
  }

  // path [a,b] と [c,d] の交わり. 空ならば {-1,-1}.

  // https://codeforces.com/problemset/problem/500/G

  pair<int, int> path_intersection(int a, int b, int c, int d) {
    int ab = lca(a, b), ac = lca(a, c), ad = lca(a, d);
    int bc = lca(b, c), bd = lca(b, d), cd = lca(c, d);
    int x = ab ^ ac ^ bc, y = ab ^ ad ^ bd; // meet(a,b,c), meet(a,b,d)

    if (x != y) return {x, y};
    int z = ac ^ ad ^ cd;
    if (x != z) x = -1;
    return {x, x};
  }
};
#line 4 "graph/ds/tree_wavelet_matrix.hpp"

// https://atcoder.jp/contests/pakencamp-2022-day1/tasks/pakencamp_2022_day1_j
// https://atcoder.jp/contests/utpc2011/tasks/utpc2011_12
template <typename TREE, bool edge, typename T, bool COMPRESS,
          typename Monoid = Monoid_Add<T>>
struct Tree_Wavelet_Matrix {
  TREE& tree;
  int N;
  using WM = Wavelet_Matrix<T, COMPRESS, Monoid_Add<T>>;
  using X = typename Monoid::value_type;
  WM wm;

  Tree_Wavelet_Matrix(TREE& tree, vc<T> A, vc<X> SUM_data = {}, int log = -1)
      : tree(tree), N(tree.N) {
    vc<X>& S = SUM_data;
    vc<T> A1;
    vc<X> S1;
    A1.resize(N);
    if (!S.empty()) S1.resize(N);
    if (!edge) {
      assert(len(A) == N && (len(S) == 0 || len(S) == N));
      FOR(v, N) A1[tree.LID[v]] = A[v];
      if (len(S) == N) { FOR(v, N) S1[tree.LID[v]] = S[v]; }
      wm.build(A1, S1, log);
    } else {
      assert(len(A) == N - 1 && (len(S) == 0 || len(S) == N - 1));
      if (!S.empty()) {
        FOR(e, N - 1) { S1[tree.LID[tree.e_to_v(e)]] = S[e]; }
      }
      FOR(e, N - 1) { A1[tree.LID[tree.e_to_v(e)]] = A[e]; }
      wm.build(A1, S1, log);
    }
  }

  // xor した結果で [a, b) に収まるものを数える
  int count_path(int s, int t, T a, T b, T xor_val = 0) {
    return wm.count(get_segments(s, t), a, b, xor_val);
  }

  // xor した結果で [a, b) に収まるものを数える
  int count_subtree(int u, T a, T b, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.count(l + edge, r, a, b, xor_val);
  }

  // xor した結果で、[L, R) の中で k>=0 番目と prefix sum
  pair<T, X> kth_value_and_sum_path(int s, int t, int k, T xor_val = 0) {
    return wm.kth_value_and_sum(get_segments(s, t), k, xor_val);
  }

  // xor した結果で、[L, R) の中で k>=0 番目と prefix sum
  pair<T, X> kth_value_and_sum_subtree(int u, int k, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.kth_value_and_sum(l + edge, r, k, xor_val);
  }

  // xor した結果で、[L, R) の中で k>=0 番目
  T kth_path(int s, int t, int k, T xor_val = 0) {
    return wm.kth(get_segments(s, t), k, xor_val);
  }

  // xor した結果で、[L, R) の中で k>=0 番目
  T kth_subtree(int u, int k, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.kth(l + edge, r, k, xor_val);
  }

  // xor した結果で、[L, R) の中で中央値。
  // LOWER = true:下側中央値、false:上側中央値
  T median_path(bool UPPER, int s, int t, T xor_val = 0) {
    return wm.median(UPPER, get_segments(s, t), xor_val);
  }

  T median_subtree(bool UPPER, int u, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.median(UPPER, l + edge, r, xor_val);
  }

  // xor した結果で [k1, k2) 番目であるところの SUM_data の和
  X sum_path(int s, int t, int k1, int k2, T xor_val = 0) {
    return wm.sum(get_segments(s, t), k1, k2, xor_val);
  }

  // xor した結果で [k1, k2) 番目であるところの SUM_data の和
  X sum_subtree(int u, int k1, int k2, T xor_val = 0) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.sum(l + edge, r, k1, k2, xor_val);
  }

  X sum_all_path(int s, int t) { return wm.sum_all(get_segments(s, t)); }

  X sum_all_subtree(int u) {
    int l = tree.LID[u], r = tree.RID[u];
    return wm.sum_all(l + edge, r);
  }

private:
  vc<pair<int, int>> get_segments(int s, int t) {
    vc<pair<int, int>> segments = tree.get_path_decomposition(s, t, edge);
    for (auto&& [a, b]: segments) {
      if (a >= b) swap(a, b);
      ++b;
    }
    return segments;
  }
};
Back to top page