Strongly Connected Components#
Color the root node of the search tree with a number:
void tarjan (int p) {
dfn[p] = low[p] = ++tim;
v[p] = 1;
s.push(p);
for (int i = head[p]; i; i = e[i].nex) {
int y = e[i].to;
if (!dfn[y]) {
tarjan(y);
low[p] = min(low[p], low[y]);
}
else if(v[y]){
low[p] = min(low[p], dfn[y]);
}
}
if (dfn[p] == low[p]) {
color[p] = p;
v[p] = 0;
while (s.top() != p) {
color[s.top()] = p;
v[s.top()] = 0;
s.pop();
}
s.pop();
}
}
Condensation#
No template...
There are many cases. Sometimes only the in-degree and out-degree can be counted.
Sometimes a new graph can be built (namespace namespace namespace)
Cut Vertex#
void tarjan (int p){
dfn[p] = low[p] = ++tim;
int kidsCnt = 0;
for (int i = head[p]; i; i = e[i].nex) {
int y = e[i].to;
if (!dfn[y]) {
++kidsCnt;
tarjan(y);
low[p] = min(low[p], low[y]);
if ((p == root && kidsCnt >= 2) || (p != root && dfn[p] <= low[y])) {
cut[p] = 1;
//++cutsCnt; will count the number repeatedly
}
}
else {
low[p] = min(low[p], dfn[y]);
}
}
}
Call:
for (int i = 1; i <= n; ++i) {
if (!dfn[i]) {
root = i;
tarjan(i);
}
}
Biconnected Components#
No template question, I don't know if it's correct...
void tarjan (int p, int fa) {
dfn[p] = low[p] = ++tim;
for (int i = head[p]; i; i = e[i].nex) {
int y = e[i].to;
if (!dfn[y]) {
st[++top] = y;
tarjan(y, p);
low[p] = min(low[p], low[y]);
if (low[y] >= dfn[u]) {
++cnt;
while (st[top] != y) {
bcc[cnt].push_back(st[top--]);
}
bcc[cnt].push_back(stack[top--]);
bcc[cnt].push_back(p);
}
}
else if (y != fa) {
low[p] = min(low[p], dfn[y]);
}
}
}
Cut Edge (Bridge)#
The initial value of newp
should be set to 1
void tarjan (int p, int ed) {//ed is the incoming edge
dfn[p] = low[p] = ++tim;
for (int i = head[p]; i; i = e[i].nex) {
int y = e[i].to;
if (!dfn[y]) {
tarjan(y, i);
low[p] = min(low[p], low[y]);
if (dfn[p] < low[y]) {
bridge[i] = bridge[i ^ 1] = 1;
}
}
else if (i != (ed ^ 1)) {
low[p] = min(low[p], dfn[y]);
}
}
}
Biconnected Components (Edge)#
First use the tarjan
for cut edges
Then there is a dfs
void dfs (int p) {
dcolor[p] = dcnt;
for (int i = head[p]; i; i = e[i].nex) {
int y = e[i].to;
if (dcolor[y] != 0 || bridge[i] == 1) {
continue;
}
dfs(y);
}
}
Use this dfs
like this
for (int i = 1; i <= n; ++i) {
if (!dcolor[i]) {
++dcnt;
dfs(i);
}
}
Number of Edges to Add to Make a Connected Graph Biconnected#
for (int i = 1; i <= m; ++i) {
if (dcolor[e[i * 2].frm] != dcolor[e[i * 2].to]) {
++out[dcolor[e[i * 2].frm]];
++out[dcolor[e[i * 2].to]];
}
}
int leaf = 0;
for (int i = 1; i <= dcnt; ++i) {
if (out[i] == 1) {
++leaf;
}
}
printf("%d\n", leaf == 1 ? 0 : (leaf + 1) / 2);