templates/prim-mst.cpp
compilable
$cat templates/prim-mst
Prim's MST
Minimum spanning tree using priority queue — greedy cut-based approach in O(E log V).
#prim#mst#minimum-spanning-tree#greedy
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pli = pair<ll, int>;
const int MAXN = 2e5 + 5;
vector<pair<int, ll>> adj[MAXN];
bool inMST[MAXN];
ll prim(int root, int n) {
ll cost = 0;
priority_queue<pli, vector<pli>, greater<pli>> pq;
pq.push({0, root});
while (!pq.empty()) {
auto [w, u] = pq.top(); pq.pop();
if (inMST[u]) continue;
inMST[u] = true;
cost += w;
for (auto &[v, wt] : adj[u])
if (!inMST[v]) pq.push({wt, v});
}
return cost;
}23 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Prim's MST
Greedy algorithm that grows the MST one edge at a time, always picking the cheapest edge crossing the cut.