class LazyPrimMST: def __init__(self, g): self.pq = MinPQ() self.marked = [] self.mst = Queue() for i in range(g.v): self.marked.append(False) self.visit(g, 0) while not self.pq.is_empty(): e = self.pq.del_min() v = e.either() w = e.other(v) if self.marked[v] and self.marked[w]: continue self.mst.enqueue(e) if not self.marked[v]: self.visit(g, v) if not self.marked[w]: self.visit(g, w) def visit(self, g, v): self.marked[v] = True for e in g.adj[v]: if not self.marked[e.other(v)]: self.pq.insert(e)
class KruskalMST: def __init__(self, g): self.mst = Queue() self.pq = MinPQ() self.uf = UF(g.v) for e in g.edges: self.pq.insert(e) while not self.pq.is_empty() and self.mst.size() < g.v - 1: e = self.pq.del_min() v = e.either() w = e.other(v) if self.uf.connected(v, w): continue self.mst.enqueue(e) self.uf.union(v, w)