Kruskal
(graph/kruskal.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/kruskal.hpp"
Overview
Kruskal’s algorithm for a minimum spanning forest of an undirected weighted graph.
The algorithm sorts edges by cost and adds them one by one if they connect two different DSU components. This greedily builds a minimum-cost set of edges that connects each connected component.
Use it when you need a minimum spanning tree (connected graph) or minimum spanning forest (possibly disconnected graph). It is especially convenient when the input is an edge list or when $M \log M$ is acceptable.
Graph Orientation
Undirected only. Build the graph with add_edge. A directed edge does not
represent the usual MST problem.
How to Use It
Build an undirected weighted graph with add_edge, then call kruskal(g).
Although the function only looks at edge endpoints and costs, using
add_directed_edge usually does not represent a normal MST problem.
The result contains these members:
| Member | Type / Signature | Meaning |
|---|---|---|
cost |
T |
Total cost of the selected forest. |
edges |
std::vector<Edge<T>> |
Selected edges. |
components |
int |
Number of connected components left after selecting edges. |
is_spanning_tree |
bool is_spanning_tree(int n) const |
Returns whether the result is one spanning tree on n vertices. |
If the graph is disconnected, the result is a minimum spanning forest and
components will be greater than 1.
Functions
| Function | Signature | Description | Complexity |
|---|---|---|---|
kruskal |
template <class T> MinimumSpanningForest<T> kruskal(const Graph<T>& g) |
Returns total cost, selected edges, and component count. | $O(M \log M)$ |
Example
#include "graph/graph.hpp"
#include "graph/kruskal.hpp"
#include <iostream>
int main() {
m1une::graph::Graph<long long> g(4);
g.add_edge(0, 1, 1);
g.add_edge(1, 2, 2);
g.add_edge(2, 3, 3);
g.add_edge(0, 3, 10);
auto mst = m1une::graph::kruskal(g);
std::cout << mst.cost << "\n"; // 6
}
Depends on
Required by
Verified with
verify/graph/cow_game.test.cpp
verify/graph/graph_algorithms.test.cpp
verify/graph/minimum_spanning_tree.test.cpp
verify/graph/range_edge_graph.test.cpp
Code
#ifndef M1UNE_GRAPH_KRUSKAL_HPP
#define M1UNE_GRAPH_KRUSKAL_HPP 1
#include <algorithm>
#include <vector>
#include "../ds/dsu/dsu.hpp"
#include "graph.hpp"
namespace m1une {
namespace graph {
template <class T>
struct MinimumSpanningForest {
T cost;
std::vector<Edge<T>> edges;
int components;
bool is_spanning_tree(int n) const {
return components <= 1 && int(edges.size()) == std::max(0, n - 1);
}
};
template <class T>
MinimumSpanningForest<T> kruskal(const Graph<T>& g) {
int n = g.size();
auto edges = g.edges();
std::sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {
return a.cost < b.cost;
});
m1une::ds::Dsu dsu(n);
MinimumSpanningForest<T> result;
result.cost = T(0);
result.components = n;
for (const auto& e : edges) {
if (dsu.same(e.from, e.to)) continue;
dsu.merge(e.from, e.to);
result.cost += e.cost;
result.edges.push_back(e);
result.components--;
}
return result;
}
} // namespace graph
} // namespace m1une
#endif // M1UNE_GRAPH_KRUSKAL_HPP#line 1 "graph/kruskal.hpp"
#include <algorithm>
#include <vector>
#line 1 "ds/dsu/dsu.hpp"
#line 5 "ds/dsu/dsu.hpp"
#include <numeric>
#include <utility>
#line 8 "ds/dsu/dsu.hpp"
namespace m1une {
namespace ds {
struct Dsu {
private:
int _n;
// parent_or_size[i] is the parent of i if it's >= 0.
// If it's < 0, then i is a root and -parent_or_size[i] is the size of the group.
std::vector<int> parent_or_size;
// Returns {new leader, absorbed leader}. The absorbed leader is -1 when
// both vertices already belong to the same component.
std::pair<int, int> merge_leaders(int a, int b) {
int x = leader(a), y = leader(b);
if (x == y) return {x, -1};
if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y);
parent_or_size[x] += parent_or_size[y];
parent_or_size[y] = x;
return {x, y};
}
public:
Dsu() : _n(0) {}
explicit Dsu(int n) : _n(n), parent_or_size(n, -1) {}
// Merges the group containing 'a' with the group containing 'b'.
// Returns the leader of the merged group.
int merge(int a, int b) {
return merge_leaders(a, b).first;
}
// Invokes callback(new_leader, absorbed_leader) after an actual merge.
// Returns the leader of the merged group.
template <class Callback>
int merge(int a, int b, Callback&& callback) {
std::pair<int, int> merged = merge_leaders(a, b);
if (merged.second != -1) callback(merged.first, merged.second);
return merged.first;
}
// Returns true if 'a' and 'b' belong to the same group.
bool same(int a, int b) {
return leader(a) == leader(b);
}
// Returns the leader (representative) of the group containing 'a'.
int leader(int a) {
if (parent_or_size[a] < 0) return a;
// Path compression
return parent_or_size[a] = leader(parent_or_size[a]);
}
// Returns the size of the group containing 'a'.
int size(int a) {
return -parent_or_size[leader(a)];
}
// Returns a list of all groups, where each group is a vector of its elements.
std::vector<std::vector<int>> groups() {
std::vector<int> leader_buf(_n), group_size(_n);
for (int i = 0; i < _n; i++) {
leader_buf[i] = leader(i);
group_size[leader_buf[i]]++;
}
std::vector<std::vector<int>> result(_n);
for (int i = 0; i < _n; i++) {
result[i].reserve(group_size[i]);
}
for (int i = 0; i < _n; i++) {
result[leader_buf[i]].push_back(i);
}
result.erase(std::remove_if(result.begin(), result.end(), [&](const std::vector<int>& v) { return v.empty(); }),
result.end());
return result;
}
};
} // namespace ds
} // namespace m1une
#line 1 "graph/graph.hpp"
#include <array>
#include <cassert>
#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 9 "graph/kruskal.hpp"
namespace m1une {
namespace graph {
template <class T>
struct MinimumSpanningForest {
T cost;
std::vector<Edge<T>> edges;
int components;
bool is_spanning_tree(int n) const {
return components <= 1 && int(edges.size()) == std::max(0, n - 1);
}
};
template <class T>
MinimumSpanningForest<T> kruskal(const Graph<T>& g) {
int n = g.size();
auto edges = g.edges();
std::sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {
return a.cost < b.cost;
});
m1une::ds::Dsu dsu(n);
MinimumSpanningForest<T> result;
result.cost = T(0);
result.components = n;
for (const auto& e : edges) {
if (dsu.same(e.from, e.to)) continue;
dsu.merge(e.from, e.to);
result.cost += e.cost;
result.edges.push_back(e);
result.components--;
}
return result;
}
} // namespace graph
} // namespace m1une