参考视频:董晓算法——Tarjan 割点
题目背景
割点
题目描述
给出一个 n n n 个点, m m m 条边的无向图,求图的割点。
输入格式
第一行输入两个正整数 n , m n,m n,m。
下面 m m m 行每行输入两个正整数 x , y x,y x,y 表示 x x x 到 y y y 有一条边。
输出格式
第一行输出割点个数。
第二行按照节点编号从小到大输出节点,用空格隔开。
样例 #1
样例输入 #1
6 7
1 2
1 3
1 4
2 5
3 5
4 5
5 6
样例输出 #1
1
5
提示
对于全部数据, 1 ≤ n ≤ 2 × 1 0 4 1\leq n \le 2\times 10^4 1≤n≤2×104, 1 ≤ m ≤ 1 × 1 0 5 1\leq m \le 1 \times 10^5 1≤m≤1×105。
点的编号均大于 0 0 0 小于等于 n n n。
tarjan图不一定联通。
概念
对图深搜时,每一个节点只访问一次,被访问过的节点与边构成搜索树
-
时间戳dfn[x]:节点x第一次被访问的顺序
-
追溯值low[x]:从节点x出发,所能访问到的最早时间戳
-
割点:对于一个无向图,如果把一个点删除后,连通块的个数增加了,那么这个点就是割点(又称割顶)。
割点判定法则:
- 如果x不是根节点,当搜索树上存在x的一个字子节点y,满足
low[y]>=dfn[x]
,那么x就是割点 - 如果x是根节点,当搜索树上存在至少两个子节点 y 1 , y 2 y_1,y_2 y1,y2,满足上述条件,那么x就是割点
low[y]>=dfn[x]
,说明从y出发,在不通过x点的前提下,不管走哪条边,都无法到达比x更早访问的节点。故删除x点后,以y为根的子树
s
u
b
t
r
e
e
(
y
)
subtree(y)
subtree(y)也就断开了,即环顶的点割得掉
反之,若low[y]<dfn[x]
,则说明y能绕行其他边到达比x更早访问的节点,x就不是割点了,即环内的点割不掉
- 当访问已经打上时间戳的节点y时,注意
low[x]=min(low[x], dfn[y])
,dfn[y]不能换成low[y],因为这是无向图,能过走回祖先节点,比如下图low[6]显然不能是1,否则dfn[5]=5<low[6]=1
代码
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<algorithm>
#include<set>
#include<stack>
#include<map>
#include<cstring>
#include<queue>
using namespace std;
const int N = 2e4 + 5, M = 1e6 + 5;
int h[N], e[M], edge[M], idx;
int dfn[N], low[N], cut[N], root, tot, cnt;
void add(int u, int v) {
e[idx] = v;
edge[idx] = h[u];
h[u] = idx++;
}
void tarjan(int x) {
dfn[x] = low[x] = ++tot;
int child = 0;
for (int i = h[x]; i != -1; i = edge[i]) {
int ne = e[i];
if (!dfn[ne]) {
tarjan(ne);
low[x] = min(low[x], low[ne]);
if (low[ne] >= dfn[x]) {
child++;
if (x != root || child > 1) cut[x] = true;
}
}
else low[x] = min(low[x], dfn[ne]);
}
}
int main()
{
memset(h, -1, sizeof(h));
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, m;
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]) root = i, tarjan(i);
}
for (int i = 1; i <= n; i++) {
if (cut[i]) ++cnt;
}
cout << cnt << "\n";
for (int i = 1; i <= n; i++) {
if (cut[i]) cout << i << " ";
}
return 0;
}