-
Notifications
You must be signed in to change notification settings - Fork 7
/
SCC.py
99 lines (81 loc) · 2.19 KB
/
SCC.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary
"""
import sys
import resource
sys.setrecursionlimit(10 ** 6)
resource.setrlimit(resource.RLIMIT_STACK, (2 ** 29, 2 ** 30))
explored = set()
source_vertex = None
finishing_time = {}
finish = 0
SCCs = {}
def DFS_rev(graph , node):
global finishing_time
global explored
global finish
explored.add(node)
for edge in graph[node]:
if edge not in explored:
DFS_rev(graph , edge)
finish += 1
finishing_time[node] = finish
def DFS_loop_rev(graph):
global explored
for node in reversed(list(graph.keys())):
if node not in explored:
DFS_rev(graph , node)
def DFS(graph , node):
global SCCs
global explored
global source_vertex
explored.add(node)
for edge in graph[node]:
if edge not in explored:
DFS(graph,edge)
SCCs[source_vertex] += 1
def DFS_loop(graph):
global explored
global SCCs
explored.clear()
global finishing_time
global source_vertex
f_time = sorted(list(graph.keys()), key = lambda f_time : finishing_time[f_time],reverse=True)
for node in f_time:
if node not in explored:
source_vertex = node
SCCs[source_vertex] = 1
DFS(graph , node)
graph = {}
rev_graph = {}
with open('SCC.txt') as f:
data = f.readlines()
for line in data:
elements = list(map(str,line[:-1].split(" ")))
try:
(graph[elements[0]]).append(elements[1])
except KeyError:
graph[str(elements[0])] = [elements[1]]
try:
(rev_graph[elements[1]]).append(elements[0])
except KeyError:
rev_graph[str(elements[1])] = [elements[0]]
if elements[0] not in rev_graph.keys():
rev_graph[str(elements[0])] = []
if elements[1] not in graph.keys():
graph[str(elements[1])] = []
f.close()
DFS_loop_rev(rev_graph)
DFS_loop(graph)
ans = ""
sccs = sorted(list(SCCs.values()), reverse =True)
for i in range(5):
try:
ans += str(sccs[i])
except IndexError:
ans+= "0"
if i < 4:
ans +=","
print(ans)