cpp-library

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

View the Project on GitHub shino16/cpp-library

:warning: graph/tree/weighted_lca.hpp

Depends on

Code

#pragma once
#include "algebra.hpp"
#include "graph/tree/dfs.hpp"
#include "bit/ilog2.hpp"

template <class M>
class weighted_lca {
 public:
  using weight_type = typename M::type;
  using edge_type = weighted_edge<weight_type>;

  template <class G, enable_if<is_same_v<weight_type, weight_t<G>>>* = nullptr>
  weighted_lca(const G& graph, int r = 0, M m = M())
      : size(graph_trait<G>(graph).size()),
        height(ilog2(size) + 1),
        m(m),
        data(height, vector<edge_type>(size)),
        depth(size) {
    data[0][r] = {r, m.unit()};
    depth[r] = 0;
    dfs(graph, r, [&](auto&& e, int p) {
      data[0][e.to] = {p, e.w()};
      depth[e.to] = depth[p] + 1;
    });
    rep(h, height - 1) rep(x, size) { data[h + 1][x] = extend(data[h][x], h); }
  }

  int lca(int u, int v) const { return paths_to_lca(u, v).first.to; }
  // product of u-v-path
  weight_type path_prod(int u, int v) const {
    auto [eu, ev] = paths_to_lca(u, v);
    return m.op(eu.w(), m.inv(ev.w()));
  }
  // signless sum of u-v-path
  weight_type path_sum(int u, int v) const {
    auto [eu, ev] = paths_to_lca(u, v);
    return m.op(eu.w(), ev.w());
  }

 private:
  int size, height;
  M m;
  vector<vector<edge_type>> data;
  vector<int> depth;

  // edge_type ascend(int v, int d) const {
  //   return ascend(edge_type{v, m.unit()}, d);
  // }
  edge_type ascend(edge_type base, int d) const {
    rep(h, height) if (d >> h & 1) base = extend(base, h);
    return base;
  }
  edge_type extend(edge_type e, int h) const {
    auto [to, w] = data[h][e.to];
    return {to, m.op(e.w(), w)};
  }
  pair<edge_type, edge_type> paths_to_lca(int u, int v) const {
    edge_type eu = {u, m.unit()}, ev = {v, m.unit()};
    if (depth[u] < depth[v])
      ev = ascend(ev, depth[v] - depth[u]);
    else if (depth[u] > depth[v])
      eu = ascend(eu, depth[u] - depth[v]);

    if (eu.to == ev.to) return {eu, ev};
    repr(h, height) {
      if (data[h][eu.to].to != data[h][ev.to].to)
        eu = extend(eu, h), ev = extend(ev, h);
    }
    return {extend(eu, 0), extend(ev, 0)};
  }
};
#line 2 "prelude.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using vc = vector<char>;
#define rep2(i, m, n) for (auto i = (m); i < (n); i++)
#define rep(i, n) rep2(i, 0, n)
#define repr2(i, m, n) for (auto i = (n); i-- > (m);)
#define repr(i, n) repr2(i, 0, n)
#define all(x) begin(x), end(x)
auto ndvec(int n, auto e) { return vector(n, e); }
auto ndvec(int n, auto ...e) { return vector(n, ndvec(e...)); }
auto comp_key(auto&& f) { return [&](auto&& a, auto&& b) { return f(a) < f(b); }; }
auto& max(const auto& a, const auto& b) { return a < b ? b : a; }
auto& min(const auto& a, const auto& b) { return b < a ? b : a; }
#if __cpp_lib_ranges
namespace R = std::ranges;
namespace V = std::views;
#endif
#line 3 "algebra.hpp"

#define CONST(val) [=] { return val; }
#define WRAP_FN(func) \
  [](auto&&... args) { return func(forward<decltype(args)>(args)...); }

template <class Unit, class Op>
struct monoid : private Unit, private Op {
  using type = decltype(declval<Unit>()());
  monoid(Unit unit, Op op) : Unit(unit), Op(op) {}
  type unit() const { return Unit::operator()(); }
  type op(type a, type b) const { return Op::operator()(a, b); }
};

template <class Unit, class Op, class Inv>
struct group : monoid<Unit, Op>, private Inv {
  using type = typename monoid<Unit, Op>::type;
  group(Unit unit, Op op, Inv inv) : monoid<Unit, Op>(unit, op), Inv(inv) {}
  type inv(type a) const { return Inv::operator()(a); }
};

template <class T>
struct addition {
  using type = T;
  type unit() const { return 0; }
  type op(type a, type b) const { return a + b; }
  type inv(type a) const { return -a; }
};

template <class T>
struct maximum {
  using type = T;
  type unit() const { return numeric_limits<T>::min(); }
  type op(type a, type b) const { return a > b ? a : b; }
};

template <class T>
struct minimum {
  using type = T;
  type unit() const { return numeric_limits<T>::max(); }
  type op(type a, type b) const { return a > b ? b : a; }
};

template <class T, T nul = -1>
struct assign {
  using type = T;
  type unit() const { return nul; }
  type op(type a, type b) const { return b == nul ? a : b; }
};
#line 3 "graph/traits.hpp"

struct unit_edge {
  int to;
  operator int() const { return to; }
  int w() const { return 1; }
};

template <class Weight>
struct weighted_edge {
  int to;
  Weight weight;
  operator int() const { return to; }
  Weight w() const { return weight; }
};

template <class Inner>
struct basic_graph {
  using weight_type = void;
  const Inner& inner;
  basic_graph(const Inner& g) : inner(g) { }
  template <class F>
  void adj(int v, F f) const {
    for (auto u : inner[v]) f(unit_edge{u});
  }
  int deg(int v) const { return inner[v].size(); }
};

template <class Inner, class Weight>
struct basic_weighted_graph {
  using weight_type = Weight;
  const Inner& inner;
  basic_weighted_graph(const Inner& g) : inner(g) { }
  template <class F>
  void adj(int v, F f) const {
    for (auto [u, w] : inner[v]) f(weighted_edge<weight_type>{u, w});
  }
  int deg(int v) const { return inner[v].size(); }
};

template <class Inner>
struct graph_trait {
  using weight_type = typename Inner::weight_type;
  const Inner& g;
  graph_trait(const Inner& g) : g(g) { }
  int size() const { return g.size(); }
  template <class F>
  void adj(int v, F f) const {
    g.adj(v, f);
  }
  decltype(auto) operator[](int v) const { return g[v]; }
};

template <class T>
constexpr bool is_weighted_v =
    !is_same_v<typename graph_trait<T>::weight_type, void>;

template <class T>
using weight_t =
    conditional_t<is_weighted_v<T>, typename graph_trait<T>::weight_type, int>;

template <class T>
using edge_t =
    conditional_t<is_weighted_v<T>, weighted_edge<weight_t<T>>, unit_edge>;

template <size_t N>
struct graph_trait<vector<int>[N]> : basic_graph<vector<int>[N]> {
  using basic_graph<vector<int>[N]>::basic_graph;
  int size() const { return N; }
};

template <>
struct graph_trait<vector<vector<int>>> : basic_graph<vector<vector<int>>> {
  using basic_graph<vector<vector<int>>>::basic_graph;
  int size() const { return this->inner.size(); }
};

template <size_t N, class Weight>
struct graph_trait<vector<pair<int, Weight>>[N]>
    : basic_weighted_graph<vector<pair<int, Weight>>[N], Weight> {
      using basic_weighted_graph<
          vector<pair<int, Weight>>[N], Weight>::basic_weighted_graph;
      int size() const { return N; }
    };

template <class Weight>
struct graph_trait<vector<vector<pair<int, Weight>>>>
    : basic_weighted_graph<vector<vector<pair<int, Weight>>>, Weight> {
  using basic_weighted_graph<
      vector<vector<pair<int, Weight>>>, Weight>::basic_weighted_graph;
  int size() const { return this->inner.size(); }
};
#line 3 "range.hpp"

template <class It>
struct range : pair<It, It> {
  using pair<It, It>::pair;
  It begin() const { return this->first; }
  It end() const { return this->second; }
  It cbegin() const { return begin(); }
  It cend() const { return end(); }
  int size() const { return this->second - this->first; }
};
#line 4 "graph/csr.hpp"

template <size_t>
struct stdin_reader;

template <class Weight = void>
class csr_graph {
 private:
  struct directed_t {};

 public:
  using weight_type = Weight;

  csr_graph() = default;
  template <class It>
  csr_graph(int n, It e, It e_last) : n(n), m(distance(e, e_last)) {
    init<false>(e, e_last);
  }
  template <size_t Size = 1 << 26>
  csr_graph(int n, int m, stdin_reader<Size>& read) : n(n), m(m) {
    auto e = read_e(read);
    init<false>(all(e));
  }

  template <class It>
  static csr_graph directed(int n, It e, It e_last) {
    return csr_graph(directed_t{}, n, e, e_last);
  }
  template <size_t Size = 1 << 26>
  static csr_graph directed(int n, int m, stdin_reader<Size>& read) {
    return csr_graph(directed_t{}, n, m, read);
  }

  template <size_t Size = 1 << 26>
  static csr_graph tree(int n, stdin_reader<Size>& read) {
    return csr_graph(n, n - 1, read);
  }
  template <size_t Size = 1 << 26>
  static csr_graph tree(stdin_reader<Size>& read) {
    int n = read;
    return csr_graph(n, n - 1, read);
  }

  int size() const { return n; }
  range<typename vector<edge_t<csr_graph>>::iterator> operator[](int v) const {
    return {ls[v], rs[v]};
  }
  int deg(int v) { return rs[v] - ls[v]; }
  template <class F>
  void adj(int v, F f) const {
    for_each(ls[v], rs[v], f);
  }

 private:
  template <class It>
  csr_graph(directed_t, int n, It e, It e_last) : n(n), m(distance(e, e_last)) {
    init<true>(e, e_last);
  }
  template <size_t Size = 1 << 26>
  csr_graph(directed_t, int n, int m, stdin_reader<Size>& read) : n(n), m(m) {
    auto e = read_e(read);
    init<true>(all(e));
  }

  vector<typename vector<edge_t<csr_graph>>::iterator> ls, rs;
  int n, m;
  vector<edge_t<csr_graph>> es;
  template <bool OneBased = true, size_t Size = 1 << 26>
  auto read_e(stdin_reader<Size>& read) {
    using E = conditional_t<is_weighted_v<csr_graph>, tuple<int, int, Weight>,
                            pair<int, int>>;
    vector<E> res(m);
    for (auto& e : res) {
      read(e);
      if (OneBased) get<0>(e)--, get<1>(e)--;
    }
    return res;
  }
  template <bool Directed, class It>
  void init(It e, It e_last) {
    if (!Directed) m *= 2;
    es.resize(m);
    ls.resize(n), rs.resize(n);
    vector<int> sz(n);
    for (auto it = e; it != e_last; it++) {
      int from = get<0>(*it), to = get<1>(*it);
      sz[from]++;
      if (!Directed) sz[to]++;
    }
    partial_sum(all(sz), sz.begin());
    rep(v, n) ls[v] = rs[v] = es.begin() + sz[v];
    for (auto it = e; it != e_last; it++) {
      int from = get<0>(*it), to = get<1>(*it);
      if constexpr (is_weighted_v<csr_graph>)
        *--ls[from] = edge_t<csr_graph>{to, get<2>(*it)};
      else
        *--ls[from] = edge_t<csr_graph>{to};
      if (!Directed) {
        if constexpr (is_weighted_v<csr_graph>)
          *--ls[to] = edge_t<csr_graph>{from, get<2>(*it)};
        else
          *--ls[to] = edge_t<csr_graph>{from};
      }
    }
  }
};
#line 3 "graph/tree/dfs.hpp"

// f(edge, par)
template <class G, class Fin, class Fout>
void dfs(const G& graph, int s, Fin&& fin, Fout&& fout) {
  graph_trait<G> g(graph);
  auto dfs_fn = [&](auto&& f, int v, int p) {
    g.adj(v, [&](auto&& e) {
      if (e.to != p) fin(e, v), f(f, e.to, v), fout(e, v);
    });
  };
  dfs_fn(dfs_fn, s, -1);
}

// f(edge, par)
template <class G, class F>
void dfs(const G& graph, int s, F&& f) {
  dfs(graph, s, f, [](auto&&, auto&&) {});
}

// f(edge, par)
template <class G, class F>
void dfs_bottom_up(const G& graph, int s, F&& f) {
  dfs(graph, s, [](auto&&, auto&&) {}, f);
}

// f(edge, par or -1)
template <class G, class F>
void dfs_ord(const G& graph, int s, F&& f) {
  f(s, -1);
  dfs(graph, s, [&](auto&& v, int p) { f(v, p); });
}

// f(edge, par or -1)
template <class G, class F>
void dfs_rev_ord(const G& graph, int s, F&& f) {
  dfs_bottom_up(graph, s, [&](auto&& v, int p) { f(v, p); });
  f(weighted_edge<weight_t<G>>{s, -1}, -1);
}
#line 3 "bit/clz.hpp"

#pragma GCC target("lzcnt")

template <class T>
int clz(T x) {
    if (!x) return sizeof(T) * 8;
    if constexpr (sizeof(T) <= sizeof(unsigned)) {
        return __builtin_clz((unsigned)x);
    } else if constexpr (sizeof(T) <= sizeof(unsigned long long)) {
        return __builtin_clzll((unsigned long long)x);
    } else if constexpr (sizeof(T) <= sizeof(unsigned long long) * 2) {
        int l = clz((unsigned long long)(x >> sizeof(unsigned long long) * 8));
        return l != sizeof(unsigned long long) * 8 ? l : l + clz((unsigned long long)x);
    }
}
#line 4 "bit/ilog2.hpp"

template <class T>
__attribute__((pure)) int ilog2(T x) { assert(x != 0); return sizeof(T) * 8 - 1 - clz(x); }

template <class T>
__attribute__((pure)) int ilog2_ceil(T x) { return x == 0 || x == 1 ? 0 : ilog2(x - 1) + 1; }

template <class T, enable_if_t<is_signed_v<T>>* = nullptr>
__attribute__((pure)) T bit_floor(T x) { return T(1) << ilog2(x); }

template <class T, enable_if_t<is_signed_v<T>>* = nullptr>
__attribute__((pure)) T bit_ceil(T x) { return T(1) << ilog2_ceil(x); }
#line 5 "graph/tree/weighted_lca.hpp"

template <class M>
class weighted_lca {
 public:
  using weight_type = typename M::type;
  using edge_type = weighted_edge<weight_type>;

  template <class G, enable_if<is_same_v<weight_type, weight_t<G>>>* = nullptr>
  weighted_lca(const G& graph, int r = 0, M m = M())
      : size(graph_trait<G>(graph).size()),
        height(ilog2(size) + 1),
        m(m),
        data(height, vector<edge_type>(size)),
        depth(size) {
    data[0][r] = {r, m.unit()};
    depth[r] = 0;
    dfs(graph, r, [&](auto&& e, int p) {
      data[0][e.to] = {p, e.w()};
      depth[e.to] = depth[p] + 1;
    });
    rep(h, height - 1) rep(x, size) { data[h + 1][x] = extend(data[h][x], h); }
  }

  int lca(int u, int v) const { return paths_to_lca(u, v).first.to; }
  // product of u-v-path
  weight_type path_prod(int u, int v) const {
    auto [eu, ev] = paths_to_lca(u, v);
    return m.op(eu.w(), m.inv(ev.w()));
  }
  // signless sum of u-v-path
  weight_type path_sum(int u, int v) const {
    auto [eu, ev] = paths_to_lca(u, v);
    return m.op(eu.w(), ev.w());
  }

 private:
  int size, height;
  M m;
  vector<vector<edge_type>> data;
  vector<int> depth;

  // edge_type ascend(int v, int d) const {
  //   return ascend(edge_type{v, m.unit()}, d);
  // }
  edge_type ascend(edge_type base, int d) const {
    rep(h, height) if (d >> h & 1) base = extend(base, h);
    return base;
  }
  edge_type extend(edge_type e, int h) const {
    auto [to, w] = data[h][e.to];
    return {to, m.op(e.w(), w)};
  }
  pair<edge_type, edge_type> paths_to_lca(int u, int v) const {
    edge_type eu = {u, m.unit()}, ev = {v, m.unit()};
    if (depth[u] < depth[v])
      ev = ascend(ev, depth[v] - depth[u]);
    else if (depth[u] > depth[v])
      eu = ascend(eu, depth[u] - depth[v]);

    if (eu.to == ev.to) return {eu, ev};
    repr(h, height) {
      if (data[h][eu.to].to != data[h][ev.to].to)
        eu = extend(eu, h), ev = extend(ev, h);
    }
    return {extend(eu, 0), extend(ev, 0)};
  }
};
Back to top page