Kruskal
Algorithm
Implementation
// Time: O(ElogE)
// Space: O(V)
class UnionFind {
vector<int> id;
int size;
public:
UnionFind(int N) : id(N), size(N) {
iota(begin(id), end(id), 0);
}
int find(int a) {
return id[a] == a ? a : (id[a] = find(id[a]));
}
void connect(int a, int b) {
int p = find(a), q = find(b);
if (p == q) return;
id[p] = q;
--size;
}
bool connected(int a, int b) {
return find(a) == find(b);
}
int getSize() { return size; }
};
int kruskal(int N, vector<vector<int>> edges) {
sort(begin(edges), end(edges), [](const vector<int> &a, const vector<int> &b) { return a[2] < b[2]; }); // Sort the edges in ascending order of weight.
UnionFind uf(N);
int cost = 0;
for (auto &e : edges) { // try the edges from smallest weight to greatest weight
int u = e[0], v = e[1], w = e[2];
if (uf.connected(u, v)) continue; // If this edge will cause cycle, skip it.
uf.connect(u, v); // otherwise, pick this edge, connect its vertices.
cost += w; // add its weight to the minimum-spanning-tree's cost
if (uf.getSize() == 1) break; // Once all nodes are connected, terminate.
}
return uf.getSize() == 1 ? cost : -1; // If all nodes are connected, return the cost; otherwise, this graph doesn't have minimum-spanning-tree.
}Problems
Reference
Last updated