Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132940 views
License: OTHER
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
4
"""
5
@source: http://codehiker.wordpress.com/2012/04/06/kosarajus-scc/
6
I made minor changs
7
"""
8
9
import sys
10
sys.setrecursionlimit(300000)
11
12
source = 'SCC.txt'
13
N = 875714
14
15
# globals
16
visited = {}
17
finish = {}
18
leader = {}
19
20
21
def get_g(source):
22
""" Read the Graph from a textfile """
23
G = {}
24
Grev = {}
25
for i in range(1, N+1):
26
G[i] = []
27
Grev[i] = []
28
fin = open(source)
29
for line in fin:
30
v1 = int(line.split()[0])
31
v2 = int(line.split()[1])
32
G[v1].append(v2)
33
Grev[v2].append(v1)
34
fin.close()
35
return G, Grev
36
37
38
def init():
39
for i in range(1, N+1):
40
visited[i] = 0
41
finish[i] = 0
42
leader[i] = 0
43
44
45
def dfs(G, i):
46
global t
47
visited[i] = 1
48
leader[i] = s
49
for j in G[i]:
50
if(visited[j] == 0):
51
dfs(G, j)
52
t = t + 1
53
finish[i] = t
54
55
56
def dfs_loop(G):
57
global t
58
global s
59
t = 0 # number of nodes processed so far
60
s = 0 # current source vertex
61
i = N
62
while(i > 0):
63
if(visited[i] == 0):
64
s = i
65
dfs(G, i)
66
i = i-1
67
68
if __name__ == "__main__":
69
init()
70
g, grev = get_g()
71
dfs_loop(grev) # THE FIRST LOOP ON REVERSE GRAPH
72
73
# construct new graph
74
newGraph = {}
75
for i in range(1, N+1):
76
temp = []
77
for x in g[i]:
78
temp.append(finish[x])
79
newGraph[finish[i]] = temp
80
81
init()
82
dfs_loop(newGraph) # THE SECOND LOOP
83
84
# statistics
85
lst = sorted(leader.values())
86
stat = []
87
pre = 0
88
for i in range(0, N-1):
89
if lst[i] != lst[i+1]:
90
stat.append(i + 1 - pre)
91
pre = i+1
92
stat.append(N-pre)
93
L = sorted(stat)
94
L.reverse()
95
print(L[0:5])
96
97