Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Advanced Algorithms HW 8 (Martin Valgur)

1654 views
1
## -*- encoding: utf-8 -*-
2
# This file was *autogenerated* from the file HW8.sagetex.sage.
3
from sage.all_cmdline import * # import sage library
4
_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.
5
import sagetex
6
_st_ = sagetex.SageTeXProcessor('HW8', version='2012/01/16 v2.3.3-69dcb0eb93de', version_check=True)
7
_st_.blockbegin()
8
try:
9
def find_sccs(V, E):
10
V = set(V)
11
found = set()
12
finished = dict()
13
reverse = False
14
15
def dfs(u, t):
16
found.add(u)
17
for a, b, w in E:
18
if reverse:
19
a, b = b, a
20
if a == u and b not in found:
21
t = dfs(b, t+_sage_const_1 )
22
finished[u] = t + _sage_const_1
23
return finished[u]
24
25
# Calculate the finishing times
26
t = _sage_const_0
27
while len(V) > len(found):
28
t = dfs((V - found).pop(), t+_sage_const_1 )
29
30
# Find the SCCs
31
sccs = []
32
reverse = True
33
found = set()
34
original_finished = finished.copy()
35
while len(V) > len(found):
36
# Find the vertex with the highest finishing time from the set of unvisited vertices
37
next_u = max((original_finished[u], u) for u in (V - found))[_sage_const_1 ]
38
prev_found = found.copy()
39
dfs(next_u, _sage_const_0 )
40
sccs.append(found - prev_found)
41
42
sccs = sorted(sccs, key=lambda scc: (-len(scc), max(scc)))
43
node_to_scc = dict()
44
for i, scc in enumerate(sccs):
45
for u in scc:
46
node_to_scc[u] = i
47
48
scc_edges = [set() for i in range(len(sccs))]
49
for a, b, w in E:
50
if node_to_scc[a] != node_to_scc[b]:
51
scc_edges[node_to_scc[a]].add(node_to_scc[b])
52
53
return sccs, node_to_scc, scc_edges, original_finished
54
except:
55
_st_.goboom(_sage_const_252 )
56
_st_.blockend()
57
_st_.blockbegin()
58
try:
59
G = DiGraph()
60
G.add_edges((
61
('A', 'D'), ('A', 'C'), ('N', 'A'), ('A', 'G'), ('D', 'B'), ('B', 'K'),
62
('K', 'D'), ('C', 'D'), ('C', 'E'), ('E', 'N'), ('N', 'G'), ('E', 'F'),
63
('E', 'H'), ('H', 'G'), ('F', 'I'), ('J', 'I'), ('M', 'F'), ('M', 'L'), ('L', 'M')))
64
E = G.edges()
65
V = G.vertices()
66
67
sccs, node_to_scc, scc_edges, finish_times = find_sccs(V, E)
68
# Calculate the topological ordering of the SCC graph
69
topo_sort = sorted(list(range(_sage_const_1 , len(sccs) + _sage_const_1 )), key=lambda i: -finish_times[iter(sccs[i-_sage_const_1 ]).next()])
70
except:
71
_st_.goboom(_sage_const_265 )
72
_st_.blockend()
73
_st_.blockbegin()
74
try:
75
H = G.plot(partition = sccs)
76
except:
77
_st_.goboom(_sage_const_268 )
78
_st_.blockend()
79
try:
80
_st_.plot(_sage_const_0 , format='notprovided', _p_=H)
81
except:
82
_st_.goboom(_sage_const_269 )
83
_st_.endofdoc()
84
85