A spanning tree connects all V vertices with V − 1 edges and no cycle. The MST has the smallest total weight.
- Kruskal — sort edges by weight, add an edge if it does not form a cycle (checked with Disjoint Set Union). O(E log E).
- Prim — start from a node, repeatedly add the cheapest edge leaving the tree (min-heap). O(E log V).
int parent[1000];
int find(int x) { return parent[x] == x ? x : parent[x] = find(parent[x]); } // path compression
bool unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return false; // same set → would make a cycle
parent[a] = b;
return true;
}
// edges = {w, u, v}
int kruskal(int n, vector<array<int,3>> edges) {
for (int i = 0; i < n; i++) parent[i] = i;
sort(edges.begin(), edges.end());
int total = 0;
for (auto [w, u, v] : edges)
if (unite(u, v)) total += w;
return total;
}