Boruvka’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 Kruskal’s Algorithm in time and space.

Tip

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

  • time and space, or
  • time and space.

Algorithm

Lemma

Let denote the set of minimum spanning trees of , denote the set of edges incident with . Then

  1. For each vertex in , choose an edge in .

  2. For each , if it is still connecting two distinct vertices, select and contract it.

  3. Solve for the resulting graph recursively.

Let be the other vertex incident with , then it is easy to prove that

Therefore, at the moment each edge is selected, it satisfies the conditions of the lemma. Applying the lemma yields that the selected edges form a minimum spanning tree.

This algorithm solves the problem in time and space.

int boruvka(int n, int m, const std::vector<int> &u, const std::vector<int> &v, const std::vector<int> &w) {
	std::vector f(m, false);
	while (std::ranges::count(f, true) < n - 1) {
		std::vector<std::vector<int>> adj(n);
		for (int i = 0; i < m; i++) {
			if (f[i]) {
				adj[u[i]].push_back(v[i]);
				adj[v[i]].push_back(u[i]);
			}
		}
 
		std::vector bel(n, -1);
		int cnt = 0;
 
		for (int i = 0; i < n; i++) {
			if (~bel[i]) {
				continue;
			}
			bel[i] = cnt;
 
			std::queue<int> q;
			q.push(i);
			while (!q.empty()) {
				int u = q.front();
				q.pop();
 
				for (int v : adj[u]) {
					if (bel[v] == -1) {
						bel[v] = cnt;
						q.push(v);
					}
				}
			}
 
			cnt++;
		}
 
		std::vector e(cnt, -1);
		for (int i = 0; i < m; i++) {
			if (bel[u[i]] == bel[v[i]]) {
				continue;
			}
 
			for (int j : {bel[u[i]], bel[v[i]]}) {
				if (e[j] == -1 || w[e[j]] > w[i]) {
					e[j] = i;
				}
			}
		}
 
		for (int i = 0; i < cnt; i++) {
			f[e[i]] = true;
		}
	}
 
	int sum = 0;
	for (int i = 0; i < m; i++) {
		if (f[i]) {
			sum += w[i];
		}
	}
	return sum;
}