-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkosaraju.cpp
More file actions
53 lines (43 loc) · 851 Bytes
/
kosaraju.cpp
File metadata and controls
53 lines (43 loc) · 851 Bytes
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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1;
int n,m;
vector<int> adj[N],rev[N];
stack<int> st;
bool visited[N];
void dfs(int u)
{
if(visited[u]) return;
visited[u] = true;
for(int v : adj[u]) dfs(v);
st.push(u);
}
void scc(int u)
{
if(visited[u]) return;
visited[u] = true;
cout << u << ' ';
for(int v : rev[u]) scc(v);
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> m;
for(int i = 0;i < m;i++)
{
int a,b;
cin >> a >> b;
adj[a].push_back(b);
rev[b].push_back(a);
}
for(int i = 1;i <= n;i++) if(!visited[i]) dfs(i);
memset(visited,0,sizeof visited);
while(!st.empty())
{
int u = st.top();
st.pop();
if(visited[u]) continue;
scc(u);
cout << '\n';
}
}