-
Notifications
You must be signed in to change notification settings - Fork 0
/
Strongly Connected Components (Kosaraju’s Algorithm).cpp
73 lines (58 loc) · 1.54 KB
/
Strongly Connected Components (Kosaraju’s Algorithm).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
// tc=3*o(n+e)
// sc=2*o(v+e)+2*o(n)
#include<bits/stdc++.h>
using namespace std;
void toposort(int node, vector<vector<int>> &adj, stack<int>& stk,vector<bool>& vis) {
vis[node]=true;
for(int i: adj[node]){
if(!vis[i]){
toposort(i,adj,stk,vis);
}
}
stk.push(node);
}
void transpose(vector<vector<int>>& adj, vector<vector<int>>& trans){
for(int i=0;i<adj.size();i++){
for(int j=0;j<adj[i].size();j++){
trans[adj[i][j]].push_back(i);
}
}
}
void dfs_trans(int node, vector<vector<int>>& adj, vector<bool>& vis, vector<int>& temp){
vis[node]=true;
temp.push_back(node);
for(int i: adj[node]){
if(!vis[i]){
dfs_trans(i,adj,vis,temp);
}
}
}
vector<vector<int>> stronglyConnectedComponents(int n, vector<vector<int>> &edges){
vector<vector<int>> adj(n,vector<int>());
for(auto i: edges){
adj[i[0]].push_back(i[1]);
}
// topo sort
stack<int> stk;
vector<bool> vis(n,false);
for(int i=0;i<n;i++){
if(!vis[i]){
toposort(i,adj,stk,vis);
}
}
// transpose
vector<vector<int>> trans(n,vector<int>());
transpose(adj,trans);
// dfs wrt finish time
vector<vector<int>> res;
fill(vis.begin(),vis.end(),false);
while(!stk.empty()){
vector<int> temp;
if(!vis[stk.top()]){
dfs_trans(stk.top(),trans,vis, temp);
}
res.push_back(temp);
stk.pop();
}
return res;
}