-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbiconnected_components.cpp
More file actions
49 lines (35 loc) · 1.27 KB
/
biconnected_components.cpp
File metadata and controls
49 lines (35 loc) · 1.27 KB
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
/*
-> Biconnected Component
-> A biconnected component of a given graph is the maximal connected subgraph which does not contain any articulation vertices.
-> The idea is to push nodes to a stack (as we visit them in the DFS tree) and when we reach back to an articulation point (or the root), we pop all the nodes visited after it to get a biconnected component.
-> ref: https://www.hackerearth.com/practice/algorithms/graphs/biconnected-components/tutorial/
*/
vector<int> adj[N];
vector<int> disc(N), low(N);
bool vis[N];
stack<int> stk;
int tim = 1;
void dfs(int x, int par) {
vis[x] = true;
disc[x] = low[x] = tim++;
stk.push(x);
for (auto c : adj[x]) {
if (c == par)
continue;
if (!vis[c]) {
dfs(c, x);
low[x] = min(low[x], low[c]);
if (low[c] >= disc[x]) {
vector<int> component;
component.pb(x);
while (stk.top() != x) {
component.pb(stk.top());
stk.pop();
}
// component[] -> vertices of the biconnected component
}
} else if (disc[c] < low[x]) {
low[x] = disc[c];
}
}
}