2021-09-07 11:37:03 +00:00
|
|
|
from __future__ import annotations
|
2021-07-06 07:08:33 +00:00
|
|
|
|
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
def dfs(u):
|
2022-10-12 22:54:20 +00:00
|
|
|
global graph, reversed_graph, scc, component, visit, stack
|
2019-10-05 05:14:13 +00:00
|
|
|
if visit[u]:
|
|
|
|
return
|
2018-10-19 12:48:28 +00:00
|
|
|
visit[u] = True
|
2021-07-06 07:08:33 +00:00
|
|
|
for v in graph[u]:
|
2018-10-19 12:48:28 +00:00
|
|
|
dfs(v)
|
|
|
|
stack.append(u)
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
def dfs2(u):
|
2022-10-12 22:54:20 +00:00
|
|
|
global graph, reversed_graph, scc, component, visit, stack
|
2019-10-05 05:14:13 +00:00
|
|
|
if visit[u]:
|
|
|
|
return
|
2018-10-19 12:48:28 +00:00
|
|
|
visit[u] = True
|
|
|
|
component.append(u)
|
2022-10-12 22:54:20 +00:00
|
|
|
for v in reversed_graph[u]:
|
2018-10-19 12:48:28 +00:00
|
|
|
dfs2(v)
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
def kosaraju():
|
2022-10-12 22:54:20 +00:00
|
|
|
global graph, reversed_graph, scc, component, visit, stack
|
2018-10-19 12:48:28 +00:00
|
|
|
for i in range(n):
|
|
|
|
dfs(i)
|
2019-10-05 05:14:13 +00:00
|
|
|
visit = [False] * n
|
2018-10-19 12:48:28 +00:00
|
|
|
for i in stack[::-1]:
|
2019-10-05 05:14:13 +00:00
|
|
|
if visit[i]:
|
|
|
|
continue
|
2018-10-19 12:48:28 +00:00
|
|
|
component = []
|
|
|
|
dfs2(i)
|
|
|
|
scc.append(component)
|
|
|
|
return scc
|
|
|
|
|
2019-07-17 04:07:25 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# n - no of nodes, m - no of edges
|
2019-10-05 05:14:13 +00:00
|
|
|
n, m = list(map(int, input().strip().split()))
|
2019-07-17 04:07:25 +00:00
|
|
|
|
2022-10-13 16:03:06 +00:00
|
|
|
graph: list[list[int]] = [[] for _ in range(n)] # graph
|
2022-10-12 22:54:20 +00:00
|
|
|
reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph
|
2019-07-17 04:07:25 +00:00
|
|
|
# input graph data (edges)
|
2022-10-13 16:03:06 +00:00
|
|
|
for _ in range(m):
|
2019-10-05 05:14:13 +00:00
|
|
|
u, v = list(map(int, input().strip().split()))
|
2021-07-06 07:08:33 +00:00
|
|
|
graph[u].append(v)
|
2022-10-12 22:54:20 +00:00
|
|
|
reversed_graph[v].append(u)
|
2019-07-17 04:07:25 +00:00
|
|
|
|
2021-09-07 11:37:03 +00:00
|
|
|
stack: list[int] = []
|
|
|
|
visit: list[bool] = [False] * n
|
|
|
|
scc: list[int] = []
|
|
|
|
component: list[int] = []
|
2019-07-17 04:07:25 +00:00
|
|
|
print(kosaraju())
|