Prim’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, or
  • time and space.

Hint

This problem can also be solved by Kruskal’s Algorithm in time and space.

Hint

This problem can also be solved by Boruvka’s Algorithm in time and space.

Algorithm 0

Lemma

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

Let be a vertex in , select an edge in and update to . Repeat this process until . Applying the lemma yields that the selected edges form a minimum spanning tree.

This algorithm solves the problem in time and space.

std::vector dist(n, inf);
dist[0] = 0;
std::vector<int> s(n);
std::iota(s.begin(), s.end(), 0);
int sum = 0;
 
while (!s.empty()) {
	int u = std::ranges::min(s, [&](int i, int j) -> bool {
		return dist[i] < dist[j];
	});
	std::erase(s, u);
 
	sum += dist[u];
	for (auto [v, w] : adj[u]) {
		dist[v] = std::min(dist[v], w);
	}
}
 
return sum;

Algorithm 1

Based on Algorithm 0, using a binary heap to maintain the structure of the graph yields an algorithm that solves the problem in time and space.

std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> q;
q.emplace(0, 0);
std::vector vis(n, false);
int sum = 0;
 
while (!q.empty()) {
	auto [d, u] = q.top();
	q.pop();
	if (vis[u]) {
		continue;
	}
	vis[u] = true;
 
	sum += d;
	for (auto [v, w] : adj[u]) {
		q.emplace(w, v);
	}
}
 
return sum;