-
Notifications
You must be signed in to change notification settings - Fork 153
/
strongly_connected_components_kosaraju.cpp
89 lines (83 loc) · 2.27 KB
/
strongly_connected_components_kosaraju.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
/**
* Description: Strictly Connected Component decomposition
* Usage: See below. O(V+E)
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
typedef vector<vector<int> > graph;
class SCC {
static const int MAX = 100005;
void transpose(vector<vector<int> > &G, vector<vector<int> > >)
{
GT.resize(G.size());
for (int i = 0; i < G.size(); i++) {
for (int j = 0; j < G[i].size(); j++) {
int v = G[i][j];
GT[v].push_back(i);
}
}
}
public:
//This fucntion can be used for toposort
void decomposeSCC(graph &G, int u, bool isVisited[], vector<int> &sortedList)
{
isVisited[u] = true;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (isVisited[v] == false) {
decomposeSCC(G, v, isVisited, sortedList);
}
}
sortedList.push_back(u);
}
vector<vector<int> > decompose(graph &G)
{
vector<vector<int> > SCCList;
bool isVisited[MAX] = {false};
vector<int> sortedList;
for (int i = 0; i < G.size(); i++) {
if (!isVisited[i]) {
decomposeSCC(G, i, isVisited, sortedList);
}
}
reverse(sortedList.begin(), sortedList.end());
vector<vector<int> > GT;
transpose(G, GT);
memset(isVisited, 0, sizeof(isVisited));
for (int i = 0; i < sortedList.size(); i++) {
int source = sortedList[i];
if (!isVisited[source]) {
vector<int> scc;
decomposeSCC(GT, source, isVisited, scc);
SCCList.push_back(scc);
}
}
return SCCList;
}
};
int main()
{
SCC S;
vector<vector<int> > G;
int n, m;
cin >> n >> m;
G.resize(n);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--, b--;
G[a].push_back(b);
}
vector<vector<int> > SCCList = S.decompose(G);
for (int i = 0; i < SCCList.size(); i++) {
for (int j = 0; j < SCCList[i].size(); j++) {
cout << SCCList[i][j] << " ";
}
cout << endl;
}
}