/
kosaraju algo for SCC.cpp
129 lines (101 loc) Β· 2.1 KB
/
kosaraju algo for SCC.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
///////////////////////////////////////////
//Question/Info
Kosaraju's Algorithm for Strongly Connected Components (SCC)
A STRONGLY CONNECTED COMPONENT IS:
A graph is said to be strongly connected if
every vertex is reachable from every other vertex.
(SINCE A COMPONENT IS A PART OF GRAPH)
The algo is:
-> Approach 1 is you start iterating graph via dfs from
backwards (using topo sort order) in the directed graph.
-> Approach 2 is you find the toposort of the graph
and then transpose your graph.
Now iterate using the toposort order in
your transpose graph and find the components.
author: srj_v
///////////////////////////////////////////
*/
#include <bits/stdc++.h>
using namespace std;
#define _IOS ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
typedef long double ld;
typedef long long int lli;
#pragma GCC optimize("Ofast")
void c_p_c()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
void topo(int node, stack<int> &st, vector<int> &vis, vector<int> adj[]) {
vis[node] = 1;
for (auto x : adj[node]) {
if (!vis[x]) {
topo(x, st, vis, adj);
}
}
st.push(node);
}
void dfs(int node, vector<int> &vis, vector<int> tra[]) {
cout << node << " ";
vis[node] = 1;
for (auto x : tra[node]) {
if (!vis[x]) {
dfs(x, vis, tra);
}
}
}
int32_t main() {
///////////
//c_p_c();
///////////
_IOS
//////////
// code
/*
int t ; cin >> t; while(t--){}
*/
int V, E;
cin >> V >> E;
vector<int> adj[V];
for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}
stack<int> st;
vector<int> vis(V, 0);
for (int i = 0; i < V; i++) {
if (!vis[i]) {
topo(i, st, vis, adj);
}
}
vector<int> tra[V]; // transpose matrix of adj
for (int i = 0; i < V; i++) {
vis[i] = 0;
for (auto x : adj[i]) {
tra[x].push_back(i);
}
}
while (!st.empty()) {
int node = st.top();
st.pop();
if (!vis[node]) {
cout << "SCC: "; // strongly connected component
dfs(node, vis, tra);
cout << endl;
}
}
/*
5 5
0 1
1 2
2 0
1 3
3 4
*/
// cerr << "time: " << clock() << " ms" << '\n';
return 0;
}