tarjan算法求无向图的桥、边双连通分量并缩点

时间:2023-03-08 16:59:46
tarjan算法求无向图的桥、边双连通分量并缩点
// tarjan算法求无向图的桥、边双连通分量并缩点
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int SIZE = ;
int head[SIZE], ver[SIZE * ], Next[SIZE * ];
int dfn[SIZE], low[SIZE], c[SIZE];
int n, m, tot, num, dcc, tc;
bool bridge[SIZE * ];
int hc[SIZE], vc[SIZE * ], nc[SIZE * ]; void add(int x, int y) {
ver[++tot] = y, Next[tot] = head[x], head[x] = tot;
} void add_c(int x, int y) {
vc[++tc] = y, nc[tc] = hc[x], hc[x] = tc;
} void tarjan(int x, int in_edge) {
dfn[x] = low[x] = ++num;
for (int i = head[x]; i; i = Next[i]) {
int y = ver[i];
//当前点未走过
if (!dfn[y]) {
tarjan(y, i);
low[x] = min(low[x], low[y]);
if (low[y] > dfn[x])
//i 与 i^1是桥
bridge[i] = bridge[i ^ ] = true;
}
//反向边更新
else if (i != (in_edge ^ ))
low[x] = min(low[x], dfn[y]);
}
} void dfs(int x) {
c[x] = dcc;
for (int i = head[x]; i; i = Next[i]) {
int y = ver[i];
if (c[y] || bridge[i]) continue;
dfs(y);
}
} int main() {
cin >> n >> m;
tot = ;
for (int i = ; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
add(x, y), add(y, x);
}
for (int i = ; i <= n; i++)
if (!dfn[i]) tarjan(i, );
for (int i = ; i < tot; i += )
if (bridge[i])//当前桥,输出连通桥的两点
printf("%d %d\n", ver[i ^ ], ver[i]);
//求边双连通分量(不存在桥)
for (int i = ; i <= n; i++)
if (!c[i]) {
++dcc;
dfs(i);
}
printf("There are %d e-DCCs.\n", dcc);
for (int i = ; i <= n; i++)
printf("%d belongs to DCC %d.\n", i, c[i]); //缩点
tc = ;
for (int i = ; i <= tot; i++) {
int x = ver[i ^ ], y = ver[i];
if (c[x] == c[y]) continue;
add_c(c[x], c[y]);
}
printf("缩点之后的森林,点数 %d,边数 %d\n", dcc, tc / );
for (int i = ; i < tc; i += )
printf("%d %d\n", vc[i ^ ], vc[i]);
}