class EdgeWeightedDirectedCycle: def __init__(self, G): self.cycle = None self.marked = [False for _ in range(G.V)] self.on_stack = [False for _ in range(G.V)] self.edge_to = [None for _ in range(G.V)] for v in range(G.V): if not self.marked[v]: self.dfs(G, v) def dfs(self, G, v): self.on_stack[v] = True self.marked[v] = True for e in G.adj[v]: w = e.To() if self.cycle is not None: return elif not self.marked[w]: print("push stack", e) self.edge_to[w] = e self.dfs(G, w) elif self.on_stack[w]: # trace back directed cycle self.cycle = Stack() f = e while f.From() != w: self.cycle.push(f) f = self.edge_to[f.From()] self.cycle.push(f) return self.on_stack[v] = False def has_cycle(self): return self.cycle is not None
def path_to(self, v): if not self.has_path_to(v): return None edges = Stack() e = self.edgeTo[v] while e != None: edges.push(e) e = self.edgeTo[e.From()] return edges
def dfs(self, G, v): self.on_stack[v] = True self.marked[v] = True for e in G.adj[v]: w = e.To() if self.cycle is not None: return elif not self.marked[w]: print("push stack", e) self.edge_to[w] = e self.dfs(G, w) elif self.on_stack[w]: # trace back directed cycle self.cycle = Stack() f = e while f.From() != w: self.cycle.push(f) f = self.edge_to[f.From()] self.cycle.push(f) return self.on_stack[v] = False
def path_to(self, v): if not self.has_path_to(v): return path = Stack() x = v while x != self.s: path.push(x) x = self.edge_to[x] path.push(s) return path
* each line contains a String and a long value, this MinPQ client * prints the m lines whose numbers are the highest. * * % python top_m.py 5 < tinyBatch.txt * Thompson 2/27/2000 4747.08 * vonNeumann 2/12/1994 4732.35 * vonNeumann 1/11/1999 4409.74 * Hoare 8/18/1992 4381.21 * vonNeumann 3/26/2002 4121.85 * """ import sys from algs4.min_pq import MinPQ from algs4.stack import Stack from algs4.transaction import Transaction M = int(sys.argv[1]) pq = MinPQ() for line in sys.stdin: pq.insert(Transaction(line)) if pq.size() > M: pq.del_min() stack = Stack() while not pq.is_empty(): stack.push(pq.del_min()) for t in stack: print(t)
def reverse_post(self): reverse = Stack() for v in self.post: reverse.push(v) return reverse