Advanced Algorithms HW 8 (Martin Valgur)
## -*- encoding: utf-8 -*-1# This file was *autogenerated* from the file HW8.sagetex.sage.2from sage.all_cmdline import * # import sage library3_sage_const_269 = Integer(269); _sage_const_268 = Integer(268); _sage_const_1 = Integer(1); _sage_const_0 = Integer(0); _sage_const_265 = Integer(265); _sage_const_252 = Integer(252)## This file (HW8.sagetex.sage) was *autogenerated* from HW8.tex with sagetex.sty version 2012/01/16 v2.3.3-69dcb0eb93de.4import sagetex5_st_ = sagetex.SageTeXProcessor('HW8', version='2012/01/16 v2.3.3-69dcb0eb93de', version_check=True)6_st_.blockbegin()7try:8def find_sccs(V, E):9V = set(V)10found = set()11finished = dict()12reverse = False1314def dfs(u, t):15found.add(u)16for a, b, w in E:17if reverse:18a, b = b, a19if a == u and b not in found:20t = dfs(b, t+_sage_const_1 )21finished[u] = t + _sage_const_122return finished[u]2324# Calculate the finishing times25t = _sage_const_026while len(V) > len(found):27t = dfs((V - found).pop(), t+_sage_const_1 )2829# Find the SCCs30sccs = []31reverse = True32found = set()33original_finished = finished.copy()34while len(V) > len(found):35# Find the vertex with the highest finishing time from the set of unvisited vertices36next_u = max((original_finished[u], u) for u in (V - found))[_sage_const_1 ]37prev_found = found.copy()38dfs(next_u, _sage_const_0 )39sccs.append(found - prev_found)4041sccs = sorted(sccs, key=lambda scc: (-len(scc), max(scc)))42node_to_scc = dict()43for i, scc in enumerate(sccs):44for u in scc:45node_to_scc[u] = i4647scc_edges = [set() for i in range(len(sccs))]48for a, b, w in E:49if node_to_scc[a] != node_to_scc[b]:50scc_edges[node_to_scc[a]].add(node_to_scc[b])5152return sccs, node_to_scc, scc_edges, original_finished53except:54_st_.goboom(_sage_const_252 )55_st_.blockend()56_st_.blockbegin()57try:58G = DiGraph()59G.add_edges((60('A', 'D'), ('A', 'C'), ('N', 'A'), ('A', 'G'), ('D', 'B'), ('B', 'K'),61('K', 'D'), ('C', 'D'), ('C', 'E'), ('E', 'N'), ('N', 'G'), ('E', 'F'),62('E', 'H'), ('H', 'G'), ('F', 'I'), ('J', 'I'), ('M', 'F'), ('M', 'L'), ('L', 'M')))63E = G.edges()64V = G.vertices()6566sccs, node_to_scc, scc_edges, finish_times = find_sccs(V, E)67# Calculate the topological ordering of the SCC graph68topo_sort = sorted(list(range(_sage_const_1 , len(sccs) + _sage_const_1 )), key=lambda i: -finish_times[iter(sccs[i-_sage_const_1 ]).next()])69except:70_st_.goboom(_sage_const_265 )71_st_.blockend()72_st_.blockbegin()73try:74H = G.plot(partition = sccs)75except:76_st_.goboom(_sage_const_268 )77_st_.blockend()78try:79_st_.plot(_sage_const_0 , format='notprovided', _p_=H)80except:81_st_.goboom(_sage_const_269 )82_st_.endofdoc()838485