2
0
Fork 0
mirror of https://github.com/MartinThoma/LaTeX-examples.git synced 2025-04-26 06:48:04 +02:00
LaTeX-examples/presentations/ICPC-Referat/Material/kosaraju.py

96 lines
1.7 KiB
Python
Raw Normal View History

2013-11-05 19:52:56 +01:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
2015-11-20 23:12:22 +01:00
"""
@source: http://codehiker.wordpress.com/2012/04/06/kosarajus-scc/
I made minor changs
2013-11-05 19:52:56 +01:00
"""
import sys
sys.setrecursionlimit(300000)
2015-11-20 23:12:22 +01:00
source = 'SCC.txt'
N = 875714
2013-11-05 19:52:56 +01:00
2015-11-20 23:12:22 +01:00
# globals
2013-11-05 19:52:56 +01:00
visited = {}
2015-11-20 23:12:22 +01:00
finish = {}
leader = {}
2013-11-05 19:52:56 +01:00
2015-11-20 23:12:22 +01:00
def get_g(source):
2013-11-05 19:52:56 +01:00
""" Read the Graph from a textfile """
2015-11-20 23:12:22 +01:00
G = {}
2013-11-05 19:52:56 +01:00
Grev = {}
2015-11-20 23:12:22 +01:00
for i in range(1, N+1):
G[i] = []
2013-11-05 19:52:56 +01:00
Grev[i] = []
fin = open(source)
for line in fin:
v1 = int(line.split()[0])
v2 = int(line.split()[1])
G[v1].append(v2)
Grev[v2].append(v1)
fin.close()
return G, Grev
2015-11-20 23:12:22 +01:00
2013-11-05 19:52:56 +01:00
def init():
2015-11-20 23:12:22 +01:00
for i in range(1, N+1):
visited[i] = 0
finish[i] = 0
leader[i] = 0
2013-11-05 19:52:56 +01:00
def dfs(G, i):
global t
2015-11-20 23:12:22 +01:00
visited[i] = 1
leader[i] = s
2013-11-05 19:52:56 +01:00
for j in G[i]:
2015-11-20 23:12:22 +01:00
if(visited[j] == 0):
dfs(G, j)
2013-11-05 19:52:56 +01:00
t = t + 1
finish[i] = t
2015-11-20 23:12:22 +01:00
2013-11-05 19:52:56 +01:00
def dfs_loop(G):
global t
global s
2015-11-20 23:12:22 +01:00
t = 0 # number of nodes processed so far
s = 0 # current source vertex
2013-11-05 19:52:56 +01:00
i = N
2015-11-20 23:12:22 +01:00
while(i > 0):
if(visited[i] == 0):
s = i
dfs(G, i)
i = i-1
2013-11-05 19:52:56 +01:00
if __name__ == "__main__":
init()
2015-11-20 23:12:22 +01:00
g, grev = get_g()
dfs_loop(grev) # THE FIRST LOOP ON REVERSE GRAPH
2013-11-05 19:52:56 +01:00
# construct new graph
newGraph = {}
for i in range(1, N+1):
temp = []
2015-11-20 23:12:22 +01:00
for x in g[i]:
temp.append(finish[x])
2013-11-05 19:52:56 +01:00
newGraph[finish[i]] = temp
init()
2015-11-20 23:12:22 +01:00
dfs_loop(newGraph) # THE SECOND LOOP
2013-11-05 19:52:56 +01:00
# statistics
2015-11-20 23:12:22 +01:00
lst = sorted(leader.values())
2013-11-05 19:52:56 +01:00
stat = []
2015-11-20 23:12:22 +01:00
pre = 0
for i in range(0, N-1):
2013-11-05 19:52:56 +01:00
if lst[i] != lst[i+1]:
stat.append(i + 1 - pre)
2015-11-20 23:12:22 +01:00
pre = i+1
2013-11-05 19:52:56 +01:00
stat.append(N-pre)
L = sorted(stat)
L.reverse()
print(L[0:5])