90 likes | 114 Views
Minimum Spanning Trees. Given an undirected graph G =( V , E ), find a graph G’ =( V , E’ ) such that E’ is a subset of E |E’| = |V| - 1 G’ is connected is minimal G’ is a minimal spanning tree . Applications: wiring a house, power grids, Internet connections.
E N D
Minimum Spanning Trees • Given an undirected graph G=(V,E), find a graph G’=(V,E’) such that • E’ is a subset of E • |E’| = |V| - 1 • G’ is connected • is minimal G’ is a minimal spanning tree. Applications: wiring a house, power grids, Internet connections CSE 373, Autumn 2001
Prim’s algorithm • Idea: Grow a tree by adding an edge from the “known” vertices to the “unknown” vertices. Pick the edge with the smallest weight. G v known CSE 373, Autumn 2001
Example 5 5 v1 v0 5 8 2 2 v3 10 1 v2 v4 10 6 5 3 v5 CSE 373, Autumn 2001
Analysis • Running time. Same as Dijkstra’s: O(|E| log |V|) • Correctness: Suppose we have a partially built tree that we know is contained in some minimum spanning tree T. Let (u,v)E, where u is “known” and v is “unknown” and has minimal cost. Then there is a MST T’ that contains the partially built tree and (u,v) that has as low a cost as T. CSE 373, Autumn 2001
Union/Find Algorithms • Equivalence Relations Suppose R is a relation defined on a set S. R is an equivalence relation if: • aRa for all aS (reflexive) • aRb iff bRa for all a,bS (symmetric) • aRb and bRc implies aRc for all a,b,cS (transitive) • Examples: CSE 373, Autumn 2001
Dynamic Equivalence S b • An equivalence relation defines a partition of S. • operations: • find(a): return the name of the equivalence class of a. • union(a,b): merge the equivalence classes of a and b. • Dynamic: the classes change because of the union operation. a CSE 373, Autumn 2001
Simple Strategy • find(i): return A[i]. O(1) • union(a,b): Let i = A[a] Let j = A[b] Scan the array and change all the i’s to j’s. O(N) • Is there a better way? Yes! CSE 373, Autumn 2001
Better Strategy • Make unions “easy” but finds “hard”. • Idea: Keep a tree for each equivalence class. • find(x) returns the root of the tree x is in. • union(x,y): merge the two trees by making one a subtree of the other. 0 1 2 3 4 5 6 7 after union(1, 2): 0 1 3 4 5 6 7 2 CSE 373, Autumn 2001
Example, continued after union(3, 4): 0 1 3 5 6 7 2 4 after union(2, 4): 0 1 5 6 7 3 2 4 implicit (array) implementation: CSE 373, Autumn 2001