Kruskal’s Algorithm is an algorithm that computes the weight of the minimum spanning tree of a connected undirected graph with edge weights in time and space.

Tip

This problem can also be solved by Prim’s Algorithm in

  • time and space, or
  • time and space.

Tip

This problem can also be solved by Borůvka’s Algorithm in time and space.

Algorithm

Lemma

Let denote the set of minimum spanning trees of , then

  1. Select an edge in .

  2. Solve for the graph obtained by contracting edge recursively.

Applying the lemma yields that the selected edges form a minimum spanning tree.

Applying an appropriate sorting algorithm (e.g., Merge Sort, Heapsort, Quicksort) to sort the edges and using a Disjoint Set Union to maintain the structure of the graph yield an algorithm that solves the problem in time and space.

int kruskal(int n, int m, const std::vector<int> &u, const std::vector<int> &v, const std::vector<int> &w) {
	auto o = std::ranges::to<std::vector>(std::views::iota(0, m));
	std::ranges::sort(o, {}, [&](int i) -> int {
		return w[i];
	});
 
	DSU dsu(n);
	return std::ranges::fold_left(o | std::views::transform([&](int i) -> int {
		return dsu.merge(u[i], v[i]) * w[i];
	}), 0, std::plus());
}