📚 The CoCalc Library - books, templates and other resources
cocalc-examples / martinthoma-latex-examples / presentations / ICPC-Referat / Material / kosaraju.py
132940 viewsLicense: OTHER
#!/usr/bin/python1# -*- coding: utf-8 -*-23"""4@source: http://codehiker.wordpress.com/2012/04/06/kosarajus-scc/5I made minor changs6"""78import sys9sys.setrecursionlimit(300000)1011source = 'SCC.txt'12N = 8757141314# globals15visited = {}16finish = {}17leader = {}181920def get_g(source):21""" Read the Graph from a textfile """22G = {}23Grev = {}24for i in range(1, N+1):25G[i] = []26Grev[i] = []27fin = open(source)28for line in fin:29v1 = int(line.split()[0])30v2 = int(line.split()[1])31G[v1].append(v2)32Grev[v2].append(v1)33fin.close()34return G, Grev353637def init():38for i in range(1, N+1):39visited[i] = 040finish[i] = 041leader[i] = 0424344def dfs(G, i):45global t46visited[i] = 147leader[i] = s48for j in G[i]:49if(visited[j] == 0):50dfs(G, j)51t = t + 152finish[i] = t535455def dfs_loop(G):56global t57global s58t = 0 # number of nodes processed so far59s = 0 # current source vertex60i = N61while(i > 0):62if(visited[i] == 0):63s = i64dfs(G, i)65i = i-16667if __name__ == "__main__":68init()69g, grev = get_g()70dfs_loop(grev) # THE FIRST LOOP ON REVERSE GRAPH7172# construct new graph73newGraph = {}74for i in range(1, N+1):75temp = []76for x in g[i]:77temp.append(finish[x])78newGraph[finish[i]] = temp7980init()81dfs_loop(newGraph) # THE SECOND LOOP8283# statistics84lst = sorted(leader.values())85stat = []86pre = 087for i in range(0, N-1):88if lst[i] != lst[i+1]:89stat.append(i + 1 - pre)90pre = i+191stat.append(N-pre)92L = sorted(stat)93L.reverse()94print(L[0:5])959697