m1une's library

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

View on GitHub

:heavy_check_mark: Sparse Table LCA
(graph/tree/sparse_table_lca.hpp)

Overview

m1une::tree::SparseTableLca<T> preprocesses an undirected rooted tree so that lca(u, v) is answered in $O(1)$ time.

It uses the standard Euler-tour reduction:

  1. Do a DFS from root.
  2. Record a vertex every time the DFS enters a vertex or returns to a parent.
  3. For each vertex v, store first[v], its first position in this Euler tour.
  4. The LCA of u and v is the minimum-depth vertex in the Euler interval between first[u] and first[v].

That minimum-depth query is static RMQ, so this structure uses ds::SparseTable internally.

Use this when you need many LCA queries and want $O(1)$ per query. If you also need kth_ancestor or jump, use RootedTree instead.

The graph should be an undirected tree built with add_edge. Inactive edges are ignored. If the graph is disconnected, only the component reachable from root gets valid LCA data.

Public Members

Member Type What is stored
root int The root used for the DFS, or -1 for an empty graph.
parent[v] int Parent of v in the rooted tree. parent[root] == -1.
parent_edge[v] int Edge id connecting parent[v] to v, or -1 at the root.
depth[v] int Number of edges from root to v.
dist[v] T Sum of edge costs from root to v.
subtree_size[v] int Number of vertices in the rooted subtree of v.
tin[v], tout[v] int DFS preorder subtree interval [tin[v], tout[v]).
order[i] int Vertex at preorder index i.
first[v] int First position of v in the Euler tour used for RMQ.
euler[i] int Vertex recorded at Euler-tour position i.

Do not confuse tin[v] and first[v]:

Methods

Method Description Complexity
SparseTableLca(g, root) Builds the Euler tour and sparse table. $O(N \log N)$
void build(g, root) Rebuilds the structure. $O(N \log N)$
int size() Returns the number of vertices in the source graph. $O(1)$
bool empty() Returns whether the source graph is empty. $O(1)$
bool is_ancestor(u, v) Returns whether u is an ancestor of v. $O(1)$
bool in_subtree(v, u) Returns whether v is in the subtree of u. $O(1)$
int lca(u, v) Returns the lowest common ancestor. $O(1)$
int dist_edges(u, v) Returns the number of edges on the path. $O(1)$
T dist_cost(u, v) Returns the sum of edge costs on the path. $O(1)$
std::pair<int, int> subtree_range(v) Returns [tin[v], tout[v]). $O(1)$

Example

#include "graph/graph.hpp"
#include "graph/tree/sparse_table_lca.hpp"
#include <iostream>

int main() {
    m1une::graph::Graph<long long> g(5);
    g.add_edge(0, 1, 2);
    g.add_edge(0, 2, 3);
    g.add_edge(1, 3, 4);
    g.add_edge(1, 4, 5);

    m1une::tree::SparseTableLca<long long> lca(g, 0);

    std::cout << lca.lca(3, 4) << "\n";       // 1
    std::cout << lca.dist_cost(3, 2) << "\n"; // 4 + 2 + 3 = 9
}

Depends on

Required by

Verified with

Code

#ifndef M1UNE_TREE_SPARSE_TABLE_LCA_HPP
#define M1UNE_TREE_SPARSE_TABLE_LCA_HPP 1

#include <algorithm>
#include <cassert>
#include <limits>
#include <utility>
#include <vector>

#include "../../ds/range_query/sparse_table.hpp"
#include "../graph.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

#endif  // M1UNE_TREE_SPARSE_TABLE_LCA_HPP
#line 1 "graph/tree/sparse_table_lca.hpp"



#include <algorithm>
#include <cassert>
#include <limits>
#include <utility>
#include <vector>

#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 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/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
Back to top page