CS252 Algorithms Friday, 26 April 2024 + Questions + Minimum spanning trees - What is one? Given connected weighted graph G = (V,E,W) W:E -> Z+ is the weight function T = (V,E') where - E' subset of E - T is a tree - among all such trees, T gives smallest total weight - What are they for? - Classic: got a map of possible cable connections Make it as cheaply as possible - Tons of more complicated algorithms in chip layout, image processing, ... that use MSTs as sub-piece - The problem In: Undirected weighted graph Out: See above Brute force? ... + Prim & Kruskal - Prim: start at a node and build outwards - Kruskal: pick the cheapest edges in order, discarding only the ones that form a cycle + Prim's Algorithm - Walkthrough [Jeff's adaptation from Wikipedia & CLRS] Prim(G=(V,E,W)) # W is the weight function on the edges Q = V E' = ∅ for v in V: O(N) C[v] = INFINITY # C for "cost to get to" F[v] = None # F for "friend" while Q != ∅: N iterations v = Q.REMOVE_MIN() O(log N) (w/ heap) if F[v] != None: E'.ADD((v,F[v])) for neighbors w of v: 2|E| iterations if w ∈ Q and W(v,w) < C[w]: C[w] = W(v,w) change a key in the heap O(log N) F[w] = v return T = (V,E',W) overall O(|E| log |V|) - Why does it work? - Runtime? + Kruskal's Algorithm [Roughly] Kruskal(G=(V,E,W)) E' = ∅ sort E in nondecreasing order by weight for (u,v) in E: # in sorted order if adding (u,v) to E' does not make a cycle: E'.ADD((u,v)) return (V,E',W) [From CLRS] Kruskal(G=(V,E,W)) E' = ∅ for v in V: MAKE-SET(v) sort E in nondecreasing order by weight for (u,v) in E: # in sorted order if FIND-SET(u) != FIND-SET(v): E'.ADD((u,v)) UNION(u,v) return (V,E',W) - Why does it work? - Runtime? this gets exciting