-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkosaraju.cpp
61 lines (55 loc) · 1.2 KB
/
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
#include <bits/stdc++.h>
using namespace std;
// Kosaraju algorithm
// Count number of strongly connected components
vector<vector<int>> graph(2002);
vector<vector<int>> graph_reverse(2002);
int n;
stack<int> pq;
bool visited[2002];
void dfs_push(int u) // use DFS to push edge can't visited other edge and push it into stack
{
visited[u] = true;
for (int x : graph[u])
if (!visited[x])
dfs_push(x);
pq.push(u);
}
void dfs(int u) // use DFS normal
{
visited[u] = true;
for (int x : graph_reverse[u])
if (!visited[x])
dfs(x);
}
int main()
{
cin.tie(0) -> sync_with_stdio(0);
int m;
cin >> n >> m;
while (m--)
{
int x, y;
cin >> x >> y;
graph[x].push_back(y);
graph_reverse[y].push_back(x); // push reverse verticle
}
for (int i = 1; i <= n; i++)
if (!visited[i])
dfs_push(i);
int cnt = 0; // create variable to count strongly connected components
memset(visited, false, sizeof(visited)); // reset visited array
while (!pq.empty())
{
int x = pq.top(); // use element on top stack
pq.pop();
if (!visited[x])
{
dfs(x);
++cnt; // increase strongly connected components by 1
}
}
return cout << cnt, 0; // print answer
}
// author: KodomoTachi [4.1.2023]
// luv Kisa