1.05k likes | 3.08k Views
Prim’s Algorithm – an Example. 7. a. d. 2. 2. 5. choosen. 4. 5. b. f. g. 1. 4. 3. 1. 7. c. e. 4. edge candidates. 7. a. d. 2. 2. 5. 4. 5. b. f. g. 1. 4. 3. 1. 7. c. e. 4. 7. a. d. 2. 2. 5. 4. 5. b. f. g. 1. 4. 3. 1. 7. c. e. 4. 7. a. d.
E N D
Prim’s Algorithm – an Example 7 a d 2 2 5 choosen 4 5 b f g 1 4 3 1 7 c e 4 edge candidates
7 a d 2 2 5 4 5 b f g 1 4 3 1 7 c e 4
7 a d 2 2 5 4 5 b f g 1 4 3 1 7 c e 4
7 a d 2 2 5 4 5 b f g 1 4 3 1 7 c e 4
7 a d 2 2 5 4 5 b f g 1 4 3 1 7 c e 4
Total weight of the MST: 14 7 a d 2 2 5 4 5 b f g 1 4 3 1 7 c e 4
Prim’s Algorithm - Description MST-Prim(G, w) choose an arbitrary rV(G) Initialize T as a tree consisting of vertex r only. whileT has < n vertices do let (u, v) be the lightest edge with u V(T) and v V(G) – V(T) T T { (u, v) } returnT Correctness follows a previous corollary: Let A be a subset of E that is included in some MST of G, and C be a connected component in the forest G = <V, A>. If (u, v) is a light edge connecting C to some other component in G , then (u, v) is safe for A.
cost(u) closest(u) u T Implementation At every iteration, maintain the following information for each vertex v in G: cost(v) is the weight of the lightest edge connecting v to T. closest(v) is the vertex y in T such that cost(v) = w(v, y). The next edge to add is (u, closest(u)). Here u is the vertex with minimum cost in V(G) – V(T).
u v z Updating Closest Vertex After adding (u,closest(u)), scan every neighbor v of u: update cost(v) if necessary. set closest(v) = u if cost(v) decreases, MST u v z new cost
Priority Queue Implementation MST-Prim(G, w) choose r V(G) for each u V(G) do cost(u) cost(r) 0 Q V(G) // Build a priority queue keyed by cost closest(r) NIL whileQ { } do dou Extract-Min(Q) for each v Adj(u) do ifv Q and w(u, v) < cost(v) thenclosest(v) u cost(v) w(u, v) // Decrease-Key
Time Q Build-Queue Extract-Min Decrease-Key Prim’s 2 Array (V) O(V) O(1) O(V ) Running Time Analysis Queue opertions: Build-Queue creates the initial queue Extract-Min extracts the vertex of minimum cost Decrease-Key decreases cost(v) for v in Q, if necessary #operations 1 V 2E Heap (V) O(lg V) O(lg V) O(E lg V)