ja / en
Overview

Kruskal

2024/07/30
1 min read

Purpose

Finds the Minimum Spanning Tree.

Time Complexity

O(ElogE)O(|E|\log|E|)

Depends

Usage

Declaration

auto res = kruskal(g);

res will contain the Minimum Spanning Tree as an UndirectedGraph.

Implementation

UndirectedGraph kruskal(UndirectedGraph &_g) {
UnionFind uf(_g.n);
UndirectedGraph res(_g.n);
sort(_g.g.begin(), _g.g.end(), [](auto &l, auto &r) { return l.cost < r.cost; });
for (auto &[u, v, cost] : _g.g) {
if (uf.merge(u, v)) {
res.add(u,v,cost);
}
}
return res;
}