4/18/2013 12 6 Minimal Spanning 9 5 Trees 14 7 8 Chapter 9 15 10 3 CPTR 318 Prim’s Algorithm Initialization 6 12 // Initialization 6 for ( each vertex v in V ) 9 5 { 5 7 9 v.value = ∞; // v 14 7 v.prev = null; // v has no predecessor v.open = true; // v is open 8 15 3 0 15 } Q = V; // Insert all vertices into priority queue 10 3 MST = Ø; // MST empty v = RandomVertex(); // Select arbitrary vertex 8 v.value = 0; Prim’s Algorithm Initialization Prim’s Algorithm // Initialization while ( Q ≠ Ø ) // While the priority queue is nonempty // Initialization { for ( each vertex v in V ) u = Q.delete_min(); u.open = false; { for ( each v adjacent to u ) v.value = ∞; // v { if ( v.open and weight(u,v) < v.value ) v.prev = null; // v has no predecessor { v.open = true; // v is open v.value = weight(u,v); } v.prev = u; Q = V; // Insert all vertices into priority queue Q.decrease_key(v); // value changed MST = Ø; // MST empty } } v = RandomVertex(); // Select arbitrary vertex } v.value = 0; for ( each v in V ) O(| V |) + O(| V | log | V |) + O(1) = O(| V | log | V |) MST = MST.insert((v, v.prev)); 1
4/18/2013 Prim’s Algorithm Prim’s Algorithm // Initialization while ( Q ≠ Ø ) // While the priority queue is nonempty { u = Q.delete_min(); O(| V |) + O(| V | log | V |) + O(1) = O(| V | log | V |) for ( each v adjacent to u ) { if ( v.open and weight(u,v) < v.value ) O(| E | log | V |) + O(| V |) = O(| E | log | V |) { v.value = weight(u,v); v.prev = u; Q.decrease_key(v); // value changed } O(| E | log | V |) } O(| E | log | V |) + O(| V |) = O(| E | log | V |) } for ( each v in V ) O(| V | 2 ) without a heap, optimal for dense graphs MST = MST.insert((v, v.prev)); 12 6 9 5 A different algorithm... 14 7 8 15 10 3 9 6 12 6 12 9 9 5 5 14 14 7 7 8 8 15 15 10 10 3 3 2
4/18/2013 Kruskal’s Algorithm Kruskal’s Algorithm // Initialization // Initialization MST = Ø; // Empty MST MST = Ø; // Empty MST // Make a forest of |V| trees // Make a forest of |V| trees // each containing a vertex in V // each containing a vertex in V for ( each vertex v in V ) for ( each vertex v in V ) create a set containing v; create a set containing v; // Build priority queue of edges // Build priority queue of edges O(| E | log | E |) for ( each edge e in E ) for ( each edge e in E ) Q.insert(e); Q.insert(e); while ( Q ≠ Ø ) // While the priority queue is nonempty while ( Q ≠ Ø ) // While the priority queue is nonempty { { (u,v) = Q.delete_min(); // Select smallest (u,v) = Q.delete_min(); // Select smallest if ( find(u) ≠ find(v) ) { // edge that if ( find(u) ≠ find(v) ) { // edge that union(u, v); // connects two union(u, v); // connects two MST.insert((u,v)); // disjoint sets MST.insert((u,v)); // disjoint sets } } } } O(1) + O(|V|) + O(| E | log | E |) + O(| E | log | E |) O(1) + O(|V|) + O(| E | log | E |) + O(| E | log | E |) = O(| E | log | E |) O(1) + O(|V|) + O(| E | log | E |) + O(| E | log | E |) = O(| E | log | E |) O(| E | log | E |) is O(|E| log |V|) ? 3
Recommend
More recommend