-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSCC.h
More file actions
44 lines (37 loc) · 881 Bytes
/
SCC.h
File metadata and controls
44 lines (37 loc) · 881 Bytes
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
#pragma once
#include <functional>
#include "Graph.h"
#include "Toposort.h"
template<typename L>
AdjList<L> invertAdjList(const AdjList<L>& g) {
AdjList<L> gInv{ g.size() };
for (int u = 0; u < g.size(); ++u) {
for (Edge<L> v : g.adj[u]) {
gInv.addEdge(v.to, u);
}
}
return gInv;
}
template<typename L>
std::vector<std::vector<int>> stronglyConnectedComponents(const AdjList<L>& g) {
std::vector<int> toposort = toposortDfs(g);
std::vector<int> vis(g.size(), false);
AdjList<L> gInv = invertAdjList(g);
std::vector<std::vector<int>> sccs;
for (int u : toposort) {
if (!vis[u]) {
std::vector<int> scc;
std::function<void(int)> dfs = [&gInv, &dfs, &vis, &scc](int u) {
if (vis[u])
return;
vis[u] = true;
scc.push_back(u);
for (Edge<L> v : gInv.adj[u])
dfs(v.to);
};
dfs(u);
sccs.push_back(scc);
}
}
return sccs;
}