-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTarjan.cpp
51 lines (48 loc) · 1.08 KB
/
Tarjan.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
class Tarjan
{
public:
Tarjan(AdjacencyList &adj) :
adj(adj), n(adj.size()), id(0),
dfn(n), low(n), vis(n), wcc(n), color(n)
{}
// strongly connected components
vector<int> &scc()
{
for (int i = 0; i < n; i++) {
if (!wcc[i]) {
dfs(i);
}
}
return color;
}
private:
void dfs(int u)
{
dfn[u] = low[u] = ++id;
wcc[u] = vis[u] = true;
s.push(u);
for (int v : adj[u]) {
if (dfn[v] == 0){
dfs(v);
low[u] = min(low[u], low[v]);
} else if (vis[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if (dfn[u] == low[u]) {
vis[u] = false ;
color[u] = u;
while (s.top() != u) {
color[s.top()] = u;
vis [s.top()] = false;
s.pop();
}
s.pop();
}
}
protected:
AdjacencyList &adj;
int n, id;
stack<int> s;
vector<int> dfn, low, vis, wcc, color;
};