def Prim(self, w, r): '''G.Prim(weight, root) -- Given weight function and an arbitrary vertex root of the graph G, compute minimum spanning tree using Prim's algorithm''' for v in self.vertices: v.weight = float("Inf") v.p = None r.weight = 0 q = min_priority_queue(self.vertices, 'weight') while q.heap_size > 0: u = q.heap_extract_min() for v in self.adj[u]: if v in q and w(u, v) < v.weight: v.p = u q.heap_decrease_key(v.index, w(u, v))
def Dijkstra(self, w, s): ''' Dijkstra's algorithm solves the single-source shortest-paths problem on a weighted, directed graph G = (V, E) for the case in which all edge weights are nonnegative. ''' self.initialize_signle_source(s) S = set() Q = min_priority_queue(self.vertices, 'd') while Q.heap_size > 1: u = Q.heap_extract_min() S = S.union({u}) for v in self.adj[u]: if v.d > u.d + w(u, v): v.d = u.d + w(u, v) v.p = u Q.heap_decrease_key(v.index, u.d + w(u, v))
def cut(self, x, y, w): '''For a given edge (x, y) contained in some minimum spanning tree, form a minimum spanning tree that contains (x, y) using a method like Prim's algorithm, and construct a cut (S, V - S) such that (x, y) is the light edge crossing the cut, S = {u: u.root = x}''' for v in self.vertices: v.weight = float("Inf") v.p = None v.root = None x.weight = 0 y.weight = 0 x.root = x y.root = y q = min_priority_queue(self.vertices, 'weight') while q.heap_size > 0: u = q.heap_extract_min() for v in self.adj[u]: if v in q and w(u, v) < v.weight: v.root = u.root q.heap_decrease_key(v.index, w(u, v)) v.p = u
def test_heap_insert(self): a = [1, 10, 3, 2, 7, 8, 9, 4, 14, 16] q = min_priority_queue(a) q.heap_extract_min() q.min_heap_insert(0) self.assertEquals(q, [0, 2, 3, 10, 4, 8, 9, 16, 14, 7])
def test_heap_decrease_key(self): a = [1, 10, 3, 2, 7, 8, 9, 4, 14, 16] q = min_priority_queue(a) q.heap_decrease_key(8, 1) self.assertEquals(q, [1, 1, 3, 2, 7, 8, 9, 10, 4, 16])
def test_heap_extract_min(self): a = [1, 10, 3, 2, 7, 8, 9, 4, 14, 16] q = min_priority_queue(a) self.assertEquals(q.heap_extract_min(), 1) self.assertEquals(q, [2, 4, 3, 10, 7, 8, 9, 16, 14, 16])
def test_heap_minimum(self): a = [1, 10, 3, 2, 7, 8, 9, 4, 14, 16] self.assertEquals(min_priority_queue(a).heap_minimum(), 1)
def test_init(self): a = [1, 10, 3, 2, 7, 8, 9, 4, 14, 16] q = min_priority_queue(a) self.assertEquals(q, [1, 2, 3, 4, 7, 8, 9, 10, 14, 16])