Virtual Tree
(graph/tree/virtual_tree.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/tree/virtual_tree.hpp"
Overview
VirtualTree<T> preprocesses a rooted weighted tree and repeatedly builds the
minimal rooted tree containing a selected set of key vertices and all LCAs
needed to connect them.
If there are K distinct key vertices, the result contains at most 2K - 1
vertices. Construction takes O(K log K) time for sorting; LCA queries are
O(1) through an internal SparseTableLca.
This is useful for tree DP when each query mentions only a small subset of the original vertices.
Result Representation
build(keys) returns VirtualTreeResult<T>. Every result array is indexed by a
compressed virtual-tree index.
| Field | Meaning |
|---|---|
vertex[i] |
Original-tree vertex represented by compressed index i. |
parent[i] |
Compressed parent index, or -1 for the virtual root. |
parent_edge_count[i] |
Number of original edges from parent[i] to i. |
parent_cost[i] |
Original weighted path cost from parent[i] to i. |
children[i] |
Compressed child indices. |
is_key[i] |
Whether this original vertex appeared in the input key set. |
Vertices are stored in original-tree preorder. Therefore every parent appears before its children, and the root has compressed index zero for a nonempty result.
Duplicate keys are removed. An empty key set produces an empty result.
result.size() and result.edge_count() return the compressed vertex and edge
counts. result.root() returns compressed index zero, while
result.root_vertex() returns its original-tree vertex id. Both root methods
return -1 for an empty result.
Methods
| Method | Description | Complexity |
|---|---|---|
VirtualTree() |
Creates an uninitialized builder. | O(1) |
VirtualTree(graph, root) |
Preprocesses the original tree. | O(N log N) |
void build_lca(graph, root) |
Replaces the original tree and preprocesses it. | O(N log N) |
int original_size() const |
Returns the original number of vertices. | O(1) |
const SparseTableLca<T>& lca_data() const |
Exposes original rooted-tree metadata. | O(1) |
result_type build(keys) |
Builds a virtual tree for the selected vertices. | O(K log K) |
All selected vertices must belong to the component reached from the preprocessing root.
Example
#include "graph/graph.hpp"
#include "graph/tree/virtual_tree.hpp"
#include <iostream>
#include <vector>
int main() {
m1une::graph::Graph<long long> graph(5);
graph.add_edge(0, 1, 3);
graph.add_edge(0, 2, 4);
graph.add_edge(1, 3, 5);
graph.add_edge(1, 4, 2);
m1une::tree::VirtualTree<long long> builder(graph, 0);
auto tree = builder.build(std::vector<int>{2, 3, 4});
for (int i = 0; i < tree.size(); i++) {
std::cout << tree.vertex[i] << ' ' << tree.parent[i] << ' '
<< tree.parent_cost[i] << '\n';
}
}
Depends on
Sparse Table
(ds/range_query/sparse_table.hpp)
Graph
(graph/graph.hpp)
Sparse Table LCA
(graph/tree/sparse_table_lca.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_VIRTUAL_TREE_HPP
#define M1UNE_TREE_VIRTUAL_TREE_HPP 1
#include <algorithm>
#include <cassert>
#include <utility>
#include <vector>
#include "../graph.hpp"
#include "sparse_table_lca.hpp"
namespace m1une {
namespace tree {
template <class T = int>
struct VirtualTreeResult {
std::vector<int> vertex;
std::vector<int> parent;
std::vector<int> parent_edge_count;
std::vector<T> parent_cost;
std::vector<std::vector<int>> children;
std::vector<bool> is_key;
int size() const {
return int(vertex.size());
}
bool empty() const {
return vertex.empty();
}
int edge_count() const {
return vertex.empty() ? 0 : int(vertex.size()) - 1;
}
int root() const {
return vertex.empty() ? -1 : 0;
}
int root_vertex() const {
return vertex.empty() ? -1 : vertex[0];
}
};
template <class T = int>
struct VirtualTree {
using cost_type = T;
using result_type = VirtualTreeResult<T>;
private:
SparseTableLca<T> _lca;
std::vector<int> _key;
std::vector<int> _vertices;
std::vector<int> _stack;
public:
VirtualTree() = default;
explicit VirtualTree(const m1une::graph::Graph<T>& graph, int root = 0) : _lca(graph, root) {}
void build_lca(const m1une::graph::Graph<T>& graph, int root = 0) {
_lca.build(graph, root);
}
int original_size() const {
return _lca.size();
}
const SparseTableLca<T>& lca_data() const {
return _lca;
}
result_type build(std::vector<int> key_vertices) {
result_type result;
if (key_vertices.empty()) return result;
auto by_tin = [&](int u, int v) { return _lca.tin[u] < _lca.tin[v]; };
for (int v : key_vertices) {
assert(0 <= v && v < _lca.size());
assert(_lca.tin[v] != -1);
}
std::sort(key_vertices.begin(), key_vertices.end(), by_tin);
key_vertices.erase(std::unique(key_vertices.begin(), key_vertices.end()), key_vertices.end());
_key = key_vertices;
_vertices = key_vertices;
_vertices.reserve(2 * _key.size());
for (int i = 1; i < int(_key.size()); i++) {
_vertices.push_back(_lca.lca(_key[i - 1], _key[i]));
}
std::sort(_vertices.begin(), _vertices.end(), by_tin);
_vertices.erase(std::unique(_vertices.begin(), _vertices.end()), _vertices.end());
int n = int(_vertices.size());
result.vertex = _vertices;
result.parent.assign(n, -1);
result.parent_edge_count.assign(n, 0);
result.parent_cost.assign(n, T(0));
result.children.assign(n, {});
result.is_key.assign(n, false);
int key_index = 0;
for (int i = 0; i < n; i++) {
while (key_index < int(_key.size()) && _lca.tin[_key[key_index]] < _lca.tin[_vertices[i]]) {
key_index++;
}
if (key_index < int(_key.size()) && _key[key_index] == _vertices[i]) result.is_key[i] = true;
}
_stack.clear();
_stack.reserve(n);
for (int i = 0; i < n; i++) {
while (!_stack.empty() && !_lca.is_ancestor(_vertices[_stack.back()], _vertices[i])) {
_stack.pop_back();
}
if (!_stack.empty()) {
int p = _stack.back();
result.parent[i] = p;
result.parent_edge_count[i] = _lca.depth[_vertices[i]] - _lca.depth[_vertices[p]];
result.parent_cost[i] = _lca.dist[_vertices[i]] - _lca.dist[_vertices[p]];
result.children[p].push_back(i);
}
_stack.push_back(i);
}
return result;
}
};
} // namespace tree
} // namespace m1une
#endif // M1UNE_TREE_VIRTUAL_TREE_HPP#line 1 "graph/tree/virtual_tree.hpp"
#include <algorithm>
#include <cassert>
#include <utility>
#include <vector>
#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 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 6 "ds/range_query/sparse_table.hpp"
#include <concepts>
#line 9 "ds/range_query/sparse_table.hpp"
#line 1 "monoid/concept.hpp"
#line 5 "monoid/concept.hpp"
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 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 11 "graph/tree/virtual_tree.hpp"
namespace m1une {
namespace tree {
template <class T = int>
struct VirtualTreeResult {
std::vector<int> vertex;
std::vector<int> parent;
std::vector<int> parent_edge_count;
std::vector<T> parent_cost;
std::vector<std::vector<int>> children;
std::vector<bool> is_key;
int size() const {
return int(vertex.size());
}
bool empty() const {
return vertex.empty();
}
int edge_count() const {
return vertex.empty() ? 0 : int(vertex.size()) - 1;
}
int root() const {
return vertex.empty() ? -1 : 0;
}
int root_vertex() const {
return vertex.empty() ? -1 : vertex[0];
}
};
template <class T = int>
struct VirtualTree {
using cost_type = T;
using result_type = VirtualTreeResult<T>;
private:
SparseTableLca<T> _lca;
std::vector<int> _key;
std::vector<int> _vertices;
std::vector<int> _stack;
public:
VirtualTree() = default;
explicit VirtualTree(const m1une::graph::Graph<T>& graph, int root = 0) : _lca(graph, root) {}
void build_lca(const m1une::graph::Graph<T>& graph, int root = 0) {
_lca.build(graph, root);
}
int original_size() const {
return _lca.size();
}
const SparseTableLca<T>& lca_data() const {
return _lca;
}
result_type build(std::vector<int> key_vertices) {
result_type result;
if (key_vertices.empty()) return result;
auto by_tin = [&](int u, int v) { return _lca.tin[u] < _lca.tin[v]; };
for (int v : key_vertices) {
assert(0 <= v && v < _lca.size());
assert(_lca.tin[v] != -1);
}
std::sort(key_vertices.begin(), key_vertices.end(), by_tin);
key_vertices.erase(std::unique(key_vertices.begin(), key_vertices.end()), key_vertices.end());
_key = key_vertices;
_vertices = key_vertices;
_vertices.reserve(2 * _key.size());
for (int i = 1; i < int(_key.size()); i++) {
_vertices.push_back(_lca.lca(_key[i - 1], _key[i]));
}
std::sort(_vertices.begin(), _vertices.end(), by_tin);
_vertices.erase(std::unique(_vertices.begin(), _vertices.end()), _vertices.end());
int n = int(_vertices.size());
result.vertex = _vertices;
result.parent.assign(n, -1);
result.parent_edge_count.assign(n, 0);
result.parent_cost.assign(n, T(0));
result.children.assign(n, {});
result.is_key.assign(n, false);
int key_index = 0;
for (int i = 0; i < n; i++) {
while (key_index < int(_key.size()) && _lca.tin[_key[key_index]] < _lca.tin[_vertices[i]]) {
key_index++;
}
if (key_index < int(_key.size()) && _key[key_index] == _vertices[i]) result.is_key[i] = true;
}
_stack.clear();
_stack.reserve(n);
for (int i = 0; i < n; i++) {
while (!_stack.empty() && !_lca.is_ancestor(_vertices[_stack.back()], _vertices[i])) {
_stack.pop_back();
}
if (!_stack.empty()) {
int p = _stack.back();
result.parent[i] = p;
result.parent_edge_count[i] = _lca.depth[_vertices[i]] - _lca.depth[_vertices[p]];
result.parent_cost[i] = _lca.dist[_vertices[i]] - _lca.dist[_vertices[p]];
result.children[p].push_back(i);
}
_stack.push_back(i);
}
return result;
}
};
} // namespace tree
} // namespace m1une