Tree
(graph/tree/tree.hpp)
- View this file on GitHub
- Last update: 2026-08-29 18:27:41+09:00
- Include:
#include "graph/tree/tree.hpp"
Overview
graph/tree/tree.hpp is a small tree bundle containing the core rooted-tree
helpers, cumulative path sums, the sparse-table LCA helper, and the diameter
routine.
For the full tree toolbox, include graph/tree/all.hpp.
Included Headers
| Header | Contents |
|---|---|
graph/tree/cumulative_sum.hpp |
Static commutative-group products and additive sums on vertex- or edge-weighted paths. |
graph/tree/euler_tour.hpp |
Lightweight rooted-tree preorder, subtree ranges, and parent/depth metadata. |
graph/tree/rooted_tree.hpp |
Rooted metadata, Euler intervals, LCA, jumps, paths, and distances. |
graph/tree/sparse_table_lca.hpp |
Euler-tour sparse-table LCA with $O(1)$ queries. |
graph/tree/diameter.hpp |
Weighted tree/forest diameter path. |
Complexity
This header is an include bundle and provides no runtime operation by itself. See the included helper pages for public interfaces and complexities.
Example
#include "graph/graph.hpp"
#include "graph/tree/tree.hpp"
#include <iostream>
int main() {
m1une::graph::Graph<int> g(3);
g.add_edge(0, 1);
g.add_edge(1, 2);
m1une::tree::RootedTree tree(g, 0);
std::cout << tree.lca(0, 2) << "\n";
}
Depends on
Sparse Table
(ds/range_query/sparse_table.hpp)
Graph
(graph/graph.hpp)
Tree Cumulative Sum
(graph/tree/cumulative_sum.hpp)
Tree Diameter
(graph/tree/diameter.hpp)
Euler Tour
(graph/tree/euler_tour.hpp)
Rooted Tree
(graph/tree/rooted_tree.hpp)
Sparse Table LCA
(graph/tree/sparse_table_lca.hpp)
Add Monoid
(monoid/add.hpp)
Monoid Concept
(monoid/concept.hpp)
Monoid Concept
(monoid/concept.hpp)
Required by
Verified with
verify/graph/cow_game.test.cpp
verify/graph/graph_algorithms.test.cpp
verify/graph/range_edge_graph.test.cpp
verify/graph/tree/tree_algorithms.test.cpp
Code
#ifndef M1UNE_TREE_TREE_HPP
#define M1UNE_TREE_TREE_HPP 1
#include "cumulative_sum.hpp"
#include "diameter.hpp"
#include "euler_tour.hpp"
#include "rooted_tree.hpp"
#include "sparse_table_lca.hpp"
#endif // M1UNE_TREE_TREE_HPP#line 1 "graph/tree/tree.hpp"
#line 1 "graph/tree/cumulative_sum.hpp"
#include <algorithm>
#include <cassert>
#include <utility>
#include <vector>
#line 1 "monoid/add.hpp"
namespace m1une {
namespace monoid {
// Monoid for addition (Range Sum).
template <typename T>
struct Add {
using value_type = T;
static constexpr bool commutative = true;
// Returns the identity element for addition, which is 0.
static constexpr T id() {
return T(0);
}
// Returns the sum of a and b.
static constexpr T op(const T& a, const T& b) {
return a + b;
}
static constexpr T inv(const T& x) {
return -x;
}
};
} // namespace monoid
} // namespace m1une
#line 1 "monoid/concept.hpp"
#include <concepts>
namespace m1une {
namespace monoid {
// Concept to check if a type satisfies the requirements of a Monoid.
// A Monoid must have a `value_type`, an identity element `id()`, and an associative binary operation `op()`.
template <typename M>
concept IsMonoid = requires(typename M::value_type a, typename M::value_type b) {
// 1. Must define `value_type`
typename M::value_type;
// 2. Must have a static method `id()` returning `value_type`
{ M::id() } -> std::same_as<typename M::value_type>;
// 3. Must have a static method `op(a, b)` returning `value_type`
{ M::op(a, b) } -> std::same_as<typename M::value_type>;
};
// Concept for groups. A type satisfying this concept must also obey the group
// laws; concepts can check the interface but not the algebraic properties.
template <typename M>
concept IsGroup = IsMonoid<M> && requires(typename M::value_type a) {
{ M::inv(a) } -> std::same_as<typename M::value_type>;
};
// Concept for commutative groups. Commutativity is a semantic requirement and
// cannot be checked by a C++ concept.
template <typename M>
concept IsCommutativeGroup = IsGroup<M>;
} // namespace monoid
} // namespace m1une
#line 1 "graph/graph.hpp"
#include <array>
#line 8 "graph/graph.hpp"
namespace m1une {
namespace graph {
template <class T = int>
struct Edge {
using cost_type = T;
int from;
int to;
T cost;
int id;
bool alive;
Edge() : from(-1), to(-1), cost(T()), id(-1), alive(true) {}
Edge(int from_, int to_, T cost_ = T(1), int id_ = -1, bool alive_ = true)
: from(from_), to(to_), cost(cost_), id(id_), alive(alive_) {}
int other(int v) const {
assert(v == from || v == to);
return from ^ to ^ v;
}
};
template <class T = int>
struct Graph {
using edge_type = Edge<T>;
using cost_type = T;
private:
struct EdgePositions {
std::array<std::pair<int, int>, 2> value{};
int size = 0;
void push_back(std::pair<int, int> position) {
assert(size < 2);
value[size++] = position;
}
};
int _n;
int _edge_count;
std::vector<std::vector<edge_type>> _g;
std::vector<EdgePositions> _edge_positions;
public:
Graph() : _n(0), _edge_count(0) {}
explicit Graph(int n) : _n(n), _edge_count(0), _g(n) {
assert(0 <= n);
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int edge_count() const {
return _edge_count;
}
int add_vertex() {
_g.emplace_back();
return _n++;
}
int add_directed_edge(int from, int to, T cost = T(1)) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int id = _edge_count++;
int idx = int(_g[from].size());
_g[from].push_back(edge_type(from, to, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({from, idx});
return id;
}
int add_edge(int u, int v, T cost = T(1)) {
assert(0 <= u && u < _n);
assert(0 <= v && v < _n);
int id = _edge_count++;
int u_idx = int(_g[u].size());
_g[u].push_back(edge_type(u, v, cost, id));
int v_idx = int(_g[v].size());
_g[v].push_back(edge_type(v, u, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({u, u_idx});
_edge_positions.back().push_back({v, v_idx});
return id;
}
void set_edge_alive(int id, bool alive) {
assert(0 <= id && id < _edge_count);
for (int i = 0; i < _edge_positions[id].size; ++i) {
auto [v, idx] = _edge_positions[id].value[i];
_g[v][idx].alive = alive;
}
}
void erase_edge(int id) {
set_edge_alive(id, false);
}
void revive_edge(int id) {
set_edge_alive(id, true);
}
bool is_edge_alive(int id) const {
assert(0 <= id && id < _edge_count);
assert(_edge_positions[id].size != 0);
auto [v, idx] = _edge_positions[id].value[0];
return _g[v][idx].alive;
}
const std::vector<edge_type>& operator[](int v) const {
assert(0 <= v && v < _n);
return _g[v];
}
std::vector<edge_type>& operator[](int v) {
assert(0 <= v && v < _n);
return _g[v];
}
const std::vector<std::vector<edge_type>>& adjacency() const {
return _g;
}
std::vector<std::vector<edge_type>>& adjacency() {
return _g;
}
std::vector<edge_type> edges(bool include_inactive = false) const {
std::vector<edge_type> result;
result.reserve(_edge_count);
std::vector<char> used(_edge_count, false);
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
if (!include_inactive && !e.alive) continue;
if (0 <= e.id && e.id < _edge_count) {
if (used[e.id]) continue;
used[e.id] = true;
}
result.push_back(e);
}
}
return result;
}
Graph reversed() const {
Graph result(_n);
result._edge_count = _edge_count;
result._edge_positions.assign(_edge_count, {});
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
int idx = int(result._g[e.to].size());
result._g[e.to].push_back(edge_type(e.to, e.from, e.cost, e.id, e.alive));
if (0 <= e.id && e.id < _edge_count) result._edge_positions[e.id].push_back({e.to, idx});
}
}
return result;
}
};
} // namespace graph
} // namespace m1une
#line 12 "graph/tree/cumulative_sum.hpp"
namespace m1une {
namespace tree {
// Static cumulative products on root paths. Values are attached to vertices by
// default; set EdgeValues to true to index them by graph edge id instead.
template <m1une::monoid::IsCommutativeGroup Group, bool EdgeValues = false>
class TreeCumulativeProduct {
public:
using value_type = typename Group::value_type;
private:
int _n = 0;
int _root = -1;
std::vector<int> _parent;
std::vector<int> _depth;
std::vector<int> _head;
std::vector<value_type> _prefix;
void check_vertex(int vertex) const {
assert(0 <= vertex && vertex < _n);
}
public:
TreeCumulativeProduct() = default;
template <class EdgeCost>
explicit TreeCumulativeProduct(
const m1une::graph::Graph<EdgeCost>& graph,
const std::vector<value_type>& values,
int root = 0
) {
build(graph, values, root);
}
template <class EdgeCost>
void build(
const m1une::graph::Graph<EdgeCost>& graph,
const std::vector<value_type>& values,
int root = 0
) {
_n = graph.size();
_root = _n == 0 ? -1 : root;
assert(
int(values.size())
== (EdgeValues ? graph.edge_count() : graph.size())
);
_parent.assign(_n, -2);
_depth.assign(_n, 0);
_head.assign(_n, -1);
_prefix.assign(_n, Group::id());
if (_n == 0) return;
assert(0 <= root && root < _n);
std::vector<int> parent_edge(_n, -1);
std::vector<int> order;
order.reserve(_n);
std::vector<int> stack = {root};
_parent[root] = -1;
while (!stack.empty()) {
int vertex = stack.back();
stack.pop_back();
order.push_back(vertex);
for (const auto& edge : graph[vertex]) {
if (!edge.alive || _parent[edge.to] != -2) continue;
_parent[edge.to] = vertex;
parent_edge[edge.to] = edge.id;
_depth[edge.to] = _depth[vertex] + 1;
stack.push_back(edge.to);
}
}
assert(int(order.size()) == _n);
std::vector<int> subtree_size(_n, 1);
std::vector<int> heavy(_n, -1);
for (int index = _n - 1; index > 0; index--) {
int vertex = order[index];
int parent = _parent[vertex];
subtree_size[parent] += subtree_size[vertex];
if (
heavy[parent] == -1
|| subtree_size[heavy[parent]] < subtree_size[vertex]
) {
heavy[parent] = vertex;
}
}
std::vector<std::pair<int, int>> starts;
starts.emplace_back(root, root);
while (!starts.empty()) {
auto [start, head] = starts.back();
starts.pop_back();
for (
int vertex = start;
vertex != -1;
vertex = heavy[vertex]
) {
_head[vertex] = head;
for (const auto& edge : graph[vertex]) {
if (
edge.alive && _parent[edge.to] == vertex
&& edge.to != heavy[vertex]
) {
starts.emplace_back(edge.to, edge.to);
}
}
}
}
if constexpr (!EdgeValues) _prefix[root] = values[root];
for (int vertex : order) {
if (vertex == root) continue;
if constexpr (EdgeValues) {
assert(0 <= parent_edge[vertex]);
_prefix[vertex] = Group::op(
_prefix[_parent[vertex]],
values[parent_edge[vertex]]
);
} else {
_prefix[vertex] = Group::op(
_prefix[_parent[vertex]],
values[vertex]
);
}
}
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int root() const {
return _root;
}
int lca(int first, int second) const {
check_vertex(first);
check_vertex(second);
while (_head[first] != _head[second]) {
if (_depth[_head[first]] < _depth[_head[second]]) {
std::swap(first, second);
}
first = _parent[_head[first]];
}
return _depth[first] < _depth[second] ? first : second;
}
// Product on the root-to-vertex path. The root vertex is included for
// vertex values; no edge lies above it in edge-value mode.
value_type prod(int vertex) const {
check_vertex(vertex);
return _prefix[vertex];
}
// Product on the simple path from first to second. Both endpoints are
// included for vertex values.
value_type prod(int first, int second) const {
int ancestor = lca(first, second);
value_type result = Group::op(_prefix[first], _prefix[second]);
result = Group::op(result, Group::inv(_prefix[ancestor]));
if constexpr (EdgeValues) {
result = Group::op(result, Group::inv(_prefix[ancestor]));
} else if (_parent[ancestor] != -1) {
result = Group::op(
result,
Group::inv(_prefix[_parent[ancestor]])
);
}
return result;
}
};
template <m1une::monoid::IsCommutativeGroup Group>
using TreeEdgeCumulativeProduct = TreeCumulativeProduct<Group, true>;
template <class T, bool EdgeValues = false>
class TreeCumulativeSum
: public TreeCumulativeProduct<m1une::monoid::Add<T>, EdgeValues> {
private:
using Base =
TreeCumulativeProduct<m1une::monoid::Add<T>, EdgeValues>;
public:
using Base::Base;
T sum(int vertex) const {
return Base::prod(vertex);
}
T sum(int first, int second) const {
return Base::prod(first, second);
}
};
template <class T>
using TreeEdgeCumulativeSum = TreeCumulativeSum<T, true>;
} // namespace tree
} // namespace m1une
#line 1 "graph/tree/diameter.hpp"
#line 6 "graph/tree/diameter.hpp"
#line 8 "graph/tree/diameter.hpp"
namespace m1une {
namespace tree {
template <class T = int>
struct TreeDiameter {
T cost;
int edge_count;
int from;
int to;
std::vector<int> vertices;
std::vector<int> edge_ids;
bool empty() const {
return vertices.empty();
}
};
namespace internal {
template <class T>
struct FarthestResult {
int vertex;
std::vector<char> seen;
std::vector<T> dist;
std::vector<int> parent;
std::vector<int> parent_edge;
};
template <class T>
FarthestResult<T> farthest_from(const m1une::graph::Graph<T>& g, int start) {
int n = g.size();
FarthestResult<T> result;
result.vertex = start;
result.seen.assign(n, false);
result.dist.assign(n, T(0));
result.parent.assign(n, -1);
result.parent_edge.assign(n, -1);
std::vector<int> stack = {start};
result.seen[start] = true;
while (!stack.empty()) {
int v = stack.back();
stack.pop_back();
if (result.dist[result.vertex] < result.dist[v]) result.vertex = v;
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (result.seen[e.to]) continue;
result.seen[e.to] = true;
result.dist[e.to] = result.dist[v] + e.cost;
result.parent[e.to] = v;
result.parent_edge[e.to] = e.id;
stack.push_back(e.to);
}
}
return result;
}
} // namespace internal
template <class T>
TreeDiameter<T> tree_diameter(const m1une::graph::Graph<T>& g) {
int n = g.size();
TreeDiameter<T> best;
best.cost = T(0);
best.edge_count = 0;
best.from = -1;
best.to = -1;
if (n == 0) return best;
std::vector<char> done(n, false);
for (int start = 0; start < n; start++) {
if (done[start]) continue;
auto first = internal::farthest_from(g, start);
for (int v = 0; v < n; v++) {
if (first.seen[v]) done[v] = true;
}
auto second = internal::farthest_from(g, first.vertex);
int a = first.vertex;
int b = second.vertex;
T cost = second.dist[b];
if (best.from != -1 && !(best.cost < cost)) continue;
best.cost = cost;
best.from = a;
best.to = b;
best.vertices.clear();
best.edge_ids.clear();
for (int v = b; v != -1; v = second.parent[v]) {
best.vertices.push_back(v);
if (v != a) best.edge_ids.push_back(second.parent_edge[v]);
}
std::reverse(best.vertices.begin(), best.vertices.end());
std::reverse(best.edge_ids.begin(), best.edge_ids.end());
best.edge_count = int(best.edge_ids.size());
}
return best;
}
} // namespace tree
} // namespace m1une
#line 1 "graph/tree/euler_tour.hpp"
#line 8 "graph/tree/euler_tour.hpp"
#line 10 "graph/tree/euler_tour.hpp"
namespace m1une {
namespace tree {
template <class T = int>
struct EulerTour {
using cost_type = T;
using edge_type = m1une::graph::Edge<T>;
int root;
std::vector<int> parent;
std::vector<int> parent_edge;
std::vector<int> depth;
std::vector<T> dist;
std::vector<int> subtree_size;
std::vector<int> tin;
std::vector<int> tout;
std::vector<int> order;
std::vector<std::vector<int>> children;
private:
int _n;
void check_vertex(int v) const {
assert(0 <= v && v < _n);
assert(tin[v] != -1);
}
public:
EulerTour() : root(-1), _n(0) {}
explicit EulerTour(const m1une::graph::Graph<T>& g, int root_ = 0) {
build(g, root_);
}
void build(const m1une::graph::Graph<T>& g, int root_ = 0) {
_n = g.size();
root = _n == 0 ? -1 : root_;
parent.assign(_n, -2);
parent_edge.assign(_n, -1);
depth.assign(_n, 0);
dist.assign(_n, T(0));
subtree_size.assign(_n, 0);
tin.assign(_n, -1);
tout.assign(_n, -1);
order.clear();
order.reserve(_n);
children.assign(_n, {});
if (_n == 0) return;
assert(0 <= root && root < _n);
struct Frame {
int v;
int state;
};
std::vector<Frame> stack;
stack.push_back({root, 0});
parent[root] = -1;
while (!stack.empty()) {
Frame frame = stack.back();
stack.pop_back();
int v = frame.v;
if (frame.state == 0) {
tin[v] = int(order.size());
order.push_back(v);
stack.push_back({v, 1});
const auto& adj = g[v];
for (int i = int(adj.size()) - 1; i >= 0; --i) {
const auto& e = adj[i];
if (!e.alive) continue;
if (parent[e.to] != -2) continue;
parent[e.to] = v;
parent_edge[e.to] = e.id;
depth[e.to] = depth[v] + 1;
dist[e.to] = dist[v] + e.cost;
children[v].push_back(e.to);
stack.push_back({e.to, 0});
}
std::reverse(children[v].begin(), children[v].end());
} else {
subtree_size[v] = 1;
for (int child : children[v]) subtree_size[v] += subtree_size[child];
tout[v] = int(order.size());
}
}
}
int size() const {
return _n;
}
int visited_size() const {
return int(order.size());
}
bool empty() const {
return _n == 0;
}
bool is_ancestor(int u, int v) const {
check_vertex(u);
check_vertex(v);
return tin[u] <= tin[v] && tout[v] <= tout[u];
}
bool in_subtree(int v, int u) const {
return is_ancestor(u, v);
}
std::pair<int, int> subtree_range(int v, bool edge = false) const {
check_vertex(v);
return {tin[v] + (edge ? 1 : 0), tout[v]};
}
std::vector<int> subtree_vertices(int v) const {
check_vertex(v);
return std::vector<int>(order.begin() + tin[v], order.begin() + tout[v]);
}
template <class F>
void for_each_subtree(int v, F f) const {
auto [l, r] = subtree_range(v);
for (int i = l; i < r; ++i) f(order[i]);
}
};
} // namespace tree
} // namespace m1une
#line 1 "graph/tree/rooted_tree.hpp"
#line 7 "graph/tree/rooted_tree.hpp"
#line 9 "graph/tree/rooted_tree.hpp"
namespace m1une {
namespace tree {
template <class T = int>
struct RootedTree {
using cost_type = T;
using edge_type = m1une::graph::Edge<T>;
int root;
std::vector<int> parent;
std::vector<int> parent_edge;
std::vector<int> depth;
std::vector<T> dist;
std::vector<int> subtree_size;
std::vector<int> tin;
std::vector<int> tout;
std::vector<int> order;
std::vector<std::vector<int>> up;
private:
int _n;
int _log;
void check_vertex(int v) const {
assert(0 <= v && v < _n);
assert(tin[v] != -1);
}
public:
RootedTree() : root(-1), _n(0), _log(0) {}
explicit RootedTree(const m1une::graph::Graph<T>& g, int root_ = 0) {
build(g, root_);
}
void build(const m1une::graph::Graph<T>& g, int root_ = 0) {
_n = g.size();
root = _n == 0 ? -1 : root_;
_log = 1;
while ((1U << _log) <= (unsigned int)(std::max(1, _n))) _log++;
parent.assign(_n, -1);
parent_edge.assign(_n, -1);
depth.assign(_n, 0);
dist.assign(_n, T(0));
subtree_size.assign(_n, 0);
tin.assign(_n, -1);
tout.assign(_n, -1);
order.clear();
order.reserve(_n);
up.assign(_log, std::vector<int>(_n, -1));
if (_n == 0) return;
assert(0 <= root && root < _n);
struct Frame {
int v;
int state;
};
std::vector<char> visited(_n, false);
std::vector<Frame> stack;
stack.push_back({root, 0});
visited[root] = true;
int timer = 0;
while (!stack.empty()) {
Frame frame = stack.back();
stack.pop_back();
int v = frame.v;
if (frame.state == 0) {
tin[v] = timer++;
order.push_back(v);
up[0][v] = parent[v];
for (int k = 1; k < _log; k++) {
int p = up[k - 1][v];
up[k][v] = p == -1 ? -1 : up[k - 1][p];
}
stack.push_back({v, 1});
const auto& adj = g[v];
for (int i = int(adj.size()) - 1; i >= 0; i--) {
const auto& e = adj[i];
if (!e.alive) continue;
if (visited[e.to]) continue;
visited[e.to] = true;
parent[e.to] = v;
parent_edge[e.to] = e.id;
depth[e.to] = depth[v] + 1;
dist[e.to] = dist[v] + e.cost;
stack.push_back({e.to, 0});
}
} else {
subtree_size[v]++;
if (parent[v] != -1) subtree_size[parent[v]] += subtree_size[v];
tout[v] = timer;
}
}
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int log() const {
return _log;
}
bool is_ancestor(int u, int v) const {
check_vertex(u);
check_vertex(v);
return tin[u] <= tin[v] && tout[v] <= tout[u];
}
bool in_subtree(int v, int u) const {
return is_ancestor(u, v);
}
int kth_ancestor(int v, int k) const {
check_vertex(v);
assert(0 <= k);
int bit = 0;
while (k > 0 && v != -1) {
if (k & 1) {
if (_log <= bit) return -1;
v = up[bit][v];
}
k >>= 1;
bit++;
}
return v;
}
int lca(int u, int v) const {
check_vertex(u);
check_vertex(v);
if (depth[u] < depth[v]) std::swap(u, v);
u = kth_ancestor(u, depth[u] - depth[v]);
if (u == v) return u;
for (int k = _log - 1; k >= 0; k--) {
if (up[k][u] != up[k][v]) {
u = up[k][u];
v = up[k][v];
}
}
return parent[u];
}
int dist_edges(int u, int v) const {
int w = lca(u, v);
return depth[u] + depth[v] - 2 * depth[w];
}
T dist_cost(int u, int v) const {
int w = lca(u, v);
return dist[u] + dist[v] - dist[w] - dist[w];
}
int jump(int from, int to, int k) const {
check_vertex(from);
check_vertex(to);
assert(0 <= k);
int w = lca(from, to);
int up_len = depth[from] - depth[w];
int down_len = depth[to] - depth[w];
if (up_len + down_len < k) return -1;
if (k <= up_len) return kth_ancestor(from, k);
return kth_ancestor(to, down_len - (k - up_len));
}
std::vector<int> path(int u, int v) const {
check_vertex(u);
check_vertex(v);
int w = lca(u, v);
std::vector<int> a, b;
for (int x = u; x != w; x = parent[x]) a.push_back(x);
a.push_back(w);
for (int x = v; x != w; x = parent[x]) b.push_back(x);
std::reverse(b.begin(), b.end());
a.insert(a.end(), b.begin(), b.end());
return a;
}
std::vector<int> path_edges(int u, int v) const {
check_vertex(u);
check_vertex(v);
int w = lca(u, v);
std::vector<int> a, b;
for (int x = u; x != w; x = parent[x]) a.push_back(parent_edge[x]);
for (int x = v; x != w; x = parent[x]) b.push_back(parent_edge[x]);
std::reverse(b.begin(), b.end());
a.insert(a.end(), b.begin(), b.end());
return a;
}
std::pair<int, int> subtree_range(int v) const {
check_vertex(v);
return {tin[v], tout[v]};
}
std::vector<int> subtree_vertices(int v) const {
check_vertex(v);
return std::vector<int>(order.begin() + tin[v], order.begin() + tout[v]);
}
};
} // namespace tree
} // namespace m1une
#line 1 "graph/tree/sparse_table_lca.hpp"
#line 6 "graph/tree/sparse_table_lca.hpp"
#include <limits>
#line 9 "graph/tree/sparse_table_lca.hpp"
#line 1 "ds/range_query/sparse_table.hpp"
#include <bit>
#line 9 "ds/range_query/sparse_table.hpp"
#line 11 "ds/range_query/sparse_table.hpp"
namespace m1une {
namespace ds {
// A Sparse Table utilizing C++20 Concepts for type safety.
// It requires a Monoid struct that satisfies `m1une::monoid::IsMonoid`.
// [IMPORTANT] For O(1) range queries to work correctly, the monoid operation MUST be idempotent.
// i.e., Monoid::op(x, x) == x must hold (e.g., Min, Max, GCD, Bitwise AND/OR).
template <m1une::monoid::IsMonoid Monoid>
struct SparseTable {
using T = typename Monoid::value_type;
private:
int _n;
std::vector<std::vector<T>> _st;
public:
// Constructs an empty sparse table.
SparseTable() : _n(0) {}
// Constructs a sparse table from an existing vector in O(N log N) time.
explicit SparseTable(const std::vector<T>& v) : _n(int(v.size())) {
if (_n == 0) return;
// Compute the maximum power of 2 needed
int max_log = std::bit_width((unsigned int)_n);
_st.assign(max_log, std::vector<T>(_n));
// Initialize the base level
for (int i = 0; i < _n; i++) {
_st[0][i] = v[i];
}
// Build the sparse table
for (int k = 1; k < max_log; k++) {
for (int i = 0; i + (1 << k) <= _n; i++) {
_st[k][i] = Monoid::op(_st[k - 1][i], _st[k - 1][i + (1 << (k - 1))]);
}
}
}
explicit SparseTable(std::vector<T>&& v) : _n(int(v.size())) {
if (_n == 0) return;
int max_log = std::bit_width((unsigned int)_n);
_st.assign(max_log, std::vector<T>(_n));
for (int i = 0; i < _n; i++) {
_st[0][i] = std::move(v[i]);
}
for (int k = 1; k < max_log; k++) {
for (int i = 0; i + (1 << k) <= _n; i++) {
_st[k][i] = Monoid::op(_st[k - 1][i], _st[k - 1][i + (1 << (k - 1))]);
}
}
}
// Constructs a sparse table from a vector of a different type U.
// It automatically adapts to the Monoid's initialization requirements:
// 1. Monoid::make(val) if it exists.
// 2. Monoid::make(val, index) if the monoid requires global indices.
// 3. static_cast<T>(val) as a fallback for simple monoids.
template <typename U>
requires (!std::same_as<U, T>) && (
requires(U x) { Monoid::make(x); } ||
requires(U x, int i) { Monoid::make(x, i); } ||
std::convertible_to<U, T>
)
explicit SparseTable(const std::vector<U>& v) : _n(int(v.size())) {
if (_n == 0) return;
int max_log = std::bit_width((unsigned int)_n);
_st.assign(max_log, std::vector<T>(_n));
// Compile-time branching based on the available make() signature
for (int i = 0; i < _n; i++) {
if constexpr (requires(U x) { Monoid::make(x); }) {
_st[0][i] = Monoid::make(v[i]);
} else if constexpr (requires(U x, int idx) { Monoid::make(x, idx); }) {
_st[0][i] = Monoid::make(v[i], i);
} else {
_st[0][i] = static_cast<T>(v[i]);
}
}
for (int k = 1; k < max_log; k++) {
for (int i = 0; i + (1 << k) <= _n; i++) {
_st[k][i] = Monoid::op(_st[k - 1][i], _st[k - 1][i + (1 << (k - 1))]);
}
}
}
// Returns the product (result of the monoid operation) in the range [l, r) in O(1) time.
// Requires the monoid operation to be idempotent.
T prod(int l, int r) const {
assert(0 <= l && l <= r && r <= _n);
if (l == r) return Monoid::id();
// Calculate the largest power of 2 less than or equal to the interval length
int k = std::bit_width((unsigned int)(r - l)) - 1;
return Monoid::op(_st[k][l], _st[k][r - (1 << k)]);
}
};
} // namespace ds
} // namespace m1une
#line 12 "graph/tree/sparse_table_lca.hpp"
namespace m1une {
namespace tree {
template <class T = int>
struct SparseTableLca {
using cost_type = T;
using edge_type = m1une::graph::Edge<T>;
int root;
std::vector<int> parent;
std::vector<int> parent_edge;
std::vector<int> depth;
std::vector<T> dist;
std::vector<int> subtree_size;
std::vector<int> tin;
std::vector<int> tout;
std::vector<int> order;
std::vector<int> first;
std::vector<int> euler;
private:
struct RmqNode {
int depth;
int vertex;
};
struct RmqMonoid {
using value_type = RmqNode;
static value_type id() {
return {std::numeric_limits<int>::max(), -1};
}
static value_type op(const value_type& a, const value_type& b) {
if (a.depth != b.depth) return a.depth < b.depth ? a : b;
return a.vertex < b.vertex ? a : b;
}
};
int _n;
m1une::ds::SparseTable<RmqMonoid> _st;
void check_vertex(int v) const {
assert(0 <= v && v < _n);
assert(first[v] != -1);
}
public:
SparseTableLca() : root(-1), _n(0) {}
explicit SparseTableLca(const m1une::graph::Graph<T>& g, int root_ = 0) {
build(g, root_);
}
void build(const m1une::graph::Graph<T>& g, int root_ = 0) {
_n = g.size();
root = _n == 0 ? -1 : root_;
parent.assign(_n, -2);
parent_edge.assign(_n, -1);
depth.assign(_n, 0);
dist.assign(_n, T(0));
subtree_size.assign(_n, 0);
tin.assign(_n, -1);
tout.assign(_n, -1);
order.clear();
order.reserve(_n);
first.assign(_n, -1);
euler.clear();
euler.reserve(std::max(0, 2 * _n - 1));
_st = m1une::ds::SparseTable<RmqMonoid>();
if (_n == 0) return;
assert(0 <= root && root < _n);
std::vector<int> it(_n, 0);
std::vector<char> visited(_n, false);
std::vector<int> stack = {root};
visited[root] = true;
parent[root] = -1;
int timer = 0;
tin[root] = timer++;
order.push_back(root);
first[root] = 0;
euler.push_back(root);
while (!stack.empty()) {
int v = stack.back();
if (it[v] < int(g[v].size())) {
const auto& e = g[v][it[v]++];
if (!e.alive) continue;
if (visited[e.to]) continue;
visited[e.to] = true;
parent[e.to] = v;
parent_edge[e.to] = e.id;
depth[e.to] = depth[v] + 1;
dist[e.to] = dist[v] + e.cost;
tin[e.to] = timer++;
order.push_back(e.to);
first[e.to] = int(euler.size());
euler.push_back(e.to);
stack.push_back(e.to);
} else {
subtree_size[v]++;
if (parent[v] != -1) subtree_size[parent[v]] += subtree_size[v];
tout[v] = timer;
stack.pop_back();
if (!stack.empty()) euler.push_back(stack.back());
}
}
std::vector<RmqNode> rmq;
rmq.reserve(euler.size());
for (int v : euler) rmq.push_back({depth[v], v});
_st = m1une::ds::SparseTable<RmqMonoid>(std::move(rmq));
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
bool is_ancestor(int u, int v) const {
check_vertex(u);
check_vertex(v);
return tin[u] <= tin[v] && tout[v] <= tout[u];
}
bool in_subtree(int v, int u) const {
return is_ancestor(u, v);
}
int lca(int u, int v) const {
check_vertex(u);
check_vertex(v);
int l = first[u], r = first[v];
if (l > r) std::swap(l, r);
return _st.prod(l, r + 1).vertex;
}
int dist_edges(int u, int v) const {
int w = lca(u, v);
return depth[u] + depth[v] - 2 * depth[w];
}
T dist_cost(int u, int v) const {
int w = lca(u, v);
return dist[u] + dist[v] - dist[w] - dist[w];
}
std::pair<int, int> subtree_range(int v) const {
check_vertex(v);
return {tin[v], tout[v]};
}
};
} // namespace tree
} // namespace m1une
#line 9 "graph/tree/tree.hpp"