Advanced Algorithms HW 8 (Martin Valgur)
## -*- encoding: utf-8 -*-1## This file (HW8.sagetex.sage) was *autogenerated* from HW8.tex with sagetex.sty version 2012/01/16 v2.3.3-69dcb0eb93de.2import sagetex3_st_ = sagetex.SageTeXProcessor('HW8', version='2012/01/16 v2.3.3-69dcb0eb93de', version_check=True)4_st_.blockbegin()5try:6def find_sccs(V, E):7V = set(V)8found = set()9finished = dict()10reverse = False1112def dfs(u, t):13found.add(u)14for a, b, w in E:15if reverse:16a, b = b, a17if a == u and b not in found:18t = dfs(b, t+1)19finished[u] = t + 120return finished[u]2122# Calculate the finishing times23t = 024while len(V) > len(found):25t = dfs((V - found).pop(), t+1)2627# Find the SCCs28sccs = []29reverse = True30found = set()31original_finished = finished.copy()32while len(V) > len(found):33# Find the vertex with the highest finishing time from the set of unvisited vertices34next_u = max((original_finished[u], u) for u in (V - found))[1]35prev_found = found.copy()36dfs(next_u, 0)37sccs.append(found - prev_found)3839sccs = sorted(sccs, key=lambda scc: (-len(scc), max(scc)))40node_to_scc = dict()41for i, scc in enumerate(sccs):42for u in scc:43node_to_scc[u] = i4445scc_edges = [set() for i in range(len(sccs))]46for a, b, w in E:47if node_to_scc[a] != node_to_scc[b]:48scc_edges[node_to_scc[a]].add(node_to_scc[b])4950return sccs, node_to_scc, scc_edges, original_finished51except:52_st_.goboom(252)53_st_.blockend()54_st_.blockbegin()55try:56G = DiGraph()57G.add_edges((58('A', 'D'), ('A', 'C'), ('N', 'A'), ('A', 'G'), ('D', 'B'), ('B', 'K'),59('K', 'D'), ('C', 'D'), ('C', 'E'), ('E', 'N'), ('N', 'G'), ('E', 'F'),60('E', 'H'), ('H', 'G'), ('F', 'I'), ('J', 'I'), ('M', 'F'), ('M', 'L'), ('L', 'M')))61E = G.edges()62V = G.vertices()6364sccs, node_to_scc, scc_edges, finish_times = find_sccs(V, E)65# Calculate the topological ordering of the SCC graph66topo_sort = sorted(list(range(1, len(sccs) + 1)), key=lambda i: -finish_times[iter(sccs[i-1]).next()])67except:68_st_.goboom(265)69_st_.blockend()70_st_.blockbegin()71try:72H = G.plot(partition = sccs)73except:74_st_.goboom(268)75_st_.blockend()76try:77_st_.plot(0, format='notprovided', _p_=H)78except:79_st_.goboom(269)80_st_.endofdoc()818283