-
Notifications
You must be signed in to change notification settings - Fork 0
/
Strongly_Connected_Component.cpp
93 lines (75 loc) · 1.33 KB
/
Strongly_Connected_Component.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
@topic - Strongly Connected Component (SCC)
@complexity - O(V+E) - Kosaraju’s algorithm
@author - Amirul islam
_
_|_ o._ o._ __|_| _. _|_
_>| ||| ||| |(_|| |(_|_>| |
_|
*/
#include <bits/stdc++.h>
using namespace std;
const int mx = 1e3;
vector <int> graph[mx], revgraph[mx];
bool vis[mx];
stack <int> st;
void dfs1(int u) {
vis[u] = 1;
for (int i = 0; i < revgraph[u].size(); i++) {
int v = revgraph[u][i];
if (vis[v] == 0) {
dfs1(v);
}
}
st.push(u);
}
void dfs2(int u) {
vis[u] = 1;
cout << u << " ";
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
if (vis[v] == 0) {
dfs2(v);
}
}
}
int main() {
int n, u, v;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> u >> v;
graph[u].push_back(v);
revgraph[v].push_back(u);
}
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n; i++) {
if (vis[i] == 0) {
dfs1(i);
}
}
memset(vis, 0, sizeof(vis));
while (!st.empty()) {
int u = st.top();
st.pop();
if (vis[u] == 0) {
dfs2(u);
cout << "\n";
}
}
return 0;
}
/*
Input:
-
5
1 0
0 2
2 1
0 3
3 4
Output:
-
4
3
0 2 1
*/