Minimum Spanning Tree.pptx
Minimum Spanning Tree.pptx
2
1. Minimum spanning tree
introduction.
3
What is a spanning tree?
4
Minimum Spanning Tree
- A minimum spanning tree is a spanning tree with the minimum sum of edge weights.
5
2. Kruskal algorithm
6
Kruskal algorithm
7
Sorted edges
(1, 2, 1)
(2, 3, 2)
(1, 3, 3)
(1, 4, 4)
(3, 4, 5)
Sorted edges
(1, 2, 1)
(2, 3, 2)
(1, 3, 3)
(1, 4, 4)
(3, 4, 5)
Sorted edges
(1, 2, 1)
(2, 3, 2)
(1, 3, 3)
(1, 4, 4)
(3, 4, 5)
Sorted edges
(1, 2, 1)
(2, 3, 2)
(1, 3, 3)
(1, 4, 4)
(3, 4, 5)
DSU - Disjoint Set Union (Union-Find)
- imagine there are n stones, n sets, initially each stone is in one set.
- A data structure supports following operations:
○ Union(u, v): given 2 stones u and v. If u and v are not in same set, merge them into 1
set.
○ Find(x): find the set that contains stone x.
12
DSU - Disjoint Set Union
13
DSU - Find
14
DSU - Union
15
for i = 0..n-1: rank[i] = 0
Union(u, v) // merge tree contain u and tree contain v
rootU = Find(u)
rootV = Find(v)
if rootU == rootV: return // same tree, do nothing
if rank[rootU] > rank[rootV]: // hang rootV under rootU
parent[rootV] = rootU // rootU becomes new tree’s root
else:
parent[rootU] = rootV // hang rootU under rootV
if rank[rootU] == rank[rootV]: // update the height of new tree
rank[rootV]+=1
Kruskal Implementation
sort(edges.begin(), edges.end()) // O(mlogm), m is number of edges
int mst = 0; // sum of weight in MST
int count = 0; // number of edge in the MST
vector<vector<int>> res;
for(auto e: edges){ // O(m)
int u = e[0];
int v = e[1];
int w = e[2];
if (find(u) != find(v)) { // can merge
mst += w;
count++;
res.push_back(e);
union(u, v);
}
}
if count != n-1 return -1 // when original graph is not connected => no MST
return mst
Space:
- O(n) for Union-find
- O(m) for edges
=>
19
Problem
- https://leetcode.com/problems/connecting-cities-with-minimum-cost/
○ https://leetcode.com/problems/connecting-cities-with-minimum-cost/submissions/131
1278102/
- https://leetcode.com/problems/min-cost-to-connect-all-points/
○ https://leetcode.com/problems/min-cost-to-connect-all-points/submissions/687940391/
○
- https://leetcode.com/problems/optimize-water-distribution-in-a-village/
20
5. Homework
21
Problem
- https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tre
e/
- Hint:
22
Problem
- https://leetcode.com/tag/minimum-spanning-tree/
-
23