参考视频:董晓算法——割边
题目描述
给出一个 n n n 个点, m m m 条边的无向图,求图的割边。
输入格式
第一行 n n n, m ( 1 ≤ n ≤ 150 m (1 \leq n\leq 150 m(1≤n≤150, 1 ≤ m ≤ 5000 ) 1 \leq m \leq 5000) 1≤m≤5000),分别表示有 n n n 个点,总共 m m m 条边。
以下 m m m 行,每行两个整数 a , b a, b a,b,表示 a a a 和 b b b 之间有一条无向边。
输出格式
输出有若干行。
每行包含两个数字 a a a, b b b,其中 a < b a<b a<b,表示 < a , b > <a,b> <a,b> 是 key road。
请注意:输出时,所有的数对 < a , b > <a,b> <a,b> 必须按照 a a a 从小到大排序输出;如果 a a a 相同,则根据 b b b 从小到大排序。
样例 #1
样例输入 #1
6 6
1 2
2 3
2 4
3 5
4 5
5 6
样例输出 #1
1 2
5 6
概念
对图深搜时,每一个节点只访问一次,被访问过的节点与边构成搜索树
- 时间戳dfn[x]:节点x第一次被访问的顺序
- 追溯值low[x]:从节点x出发,所能访问到的最早时间戳
- **割边:**对于一个无向图,如果删掉一条边后图的连通块数量增加了,则称这条边为桥或割边
割边判定法则:
- 当搜索树上存在x的一个子节点y,满足
low[y]<dfn[x]
,则称 ( x , y ) (x,y) (x,y)这条边为割边 low[y]>dfn[x]
,说明从y出发,在不经过 ( x , y ) (x,y) (x,y)这条边的前提下,不管走哪条边,都无法到达x或更早访问的节点,故删除 ( x , y ) (x,y) (x,y)这条边,以y为根的子树 s u b t r e e ( y ) subtree(y) subtree(y)也就断开了,即环外的边割得断- 反之,若
low[y]<=dfn[x]
,则说明y能绕行其他边到达x或更早访问的节点, ( x , y ) (x,y) (x,y)就不是割边了,即环内的边割不断 - 搜索过程中不能沿着无向边的反边走回(可沿重边返回)
![image-20220622171404391](https://zh-typora.oss-cn-guangzhou.aliyuncs.com/typora-img/image-20220622171404391.png)
![image-20220622174401296](https://zh-typora.oss-cn-guangzhou.aliyuncs.com/typora-img/image-20220622174401296.png)
代码
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<algorithm>
#include<set>
#include<stack>
#include<map>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const int N = 205, M = 1e4 + 5;
int h[N], e[M], edge[M], idx;
int low[N], dfn[N], tot;
vector<pair<int, int>> bri;
int n, m;
void add(int u, int v) {
e[idx] = v;
edge[idx] = h[u];
h[u] = idx++;
}
void tarjan(int x, int in_edg) {
low[x] = dfn[x] = ++tot;
for (int i = h[x]; i != -1; i = edge[i]) {
int ne = e[i];
if (!dfn[ne]) {
tarjan(ne, i);
low[x] = min(low[x], low[ne]);
if (low[ne] > dfn[x]) bri.push_back({ min(x, ne), max(x, ne) });
}
else if (i != (in_edg ^ 1)) {
low[x] = min(low[x], dfn[ne]);
}
}
}
int main()
{
memset(h, -1, sizeof(h));
cin >> n >> m;
while (m--) {
int u, v;
cin >> u >> v;
add(u, v);
add(v, u);
}
for (int i = 1; i <= n; i++) {
if (!dfn[i]) tarjan(i, -1);
}
sort(bri.begin(), bri.end());
for (auto p : bri) cout << p.first << " " << p.second << "\n";
return 0;
}