题目大意:
求 n n n个点 m m m条边的无向图的割点
解题思路:
T
a
r
j
a
n
Tarjan
Tarjan
注意:由于图不一定联通,所以我们要在每个联通块都跑一遍
T
a
r
j
a
n
Tarjan
Tarjan
A c c e p t e d c o d e : Accepted\ code: Accepted code:
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
struct Line {
int to, next;
}e[200005];
int n, m, cnt, tot;
int last[20005], dfn[20005], low[20005], vis[20005];
inline int read() {
int f = 0, flag = 1; char c = getchar();
while (isdigit(c) == 0) flag = (c == '-') ? -1 : 1, c = getchar();
while (isdigit(c) != 0) f = (f<<1) + (f<<3) + c - 48, c = getchar();
return flag * f;
}
inline void add(int x, int y) { //建图
x = read(), y = read();
e[++cnt].to = y; e[cnt].next = last[x]; last[x] = cnt;
e[++cnt].to = x; e[cnt].next = last[y]; last[y] = cnt;
}
void Tarjan(int x, int fa) { //x表示当前节点,fa表示父节点
int subtree = 0;//子树数量
dfn[x] = low[x] = ++tot;//记录时间戳
for (int i = last[x]; ~i; i = e[i].next) { //枚举每一条边
int y = e[i].to; //y是这条边的终点
if (!dfn[y]) { //如果没有访问过y
Tarjan(y, x); //以y为当前节点
low[x] = min(low[x], low[y]);
//low[i]表示i点能回溯到的最小的dfn,因为x,y之间有连边,所以x能去到y
//所以y能回溯到的点x也能回溯到
//因为我们找的是能回溯到的最小的dfn所以dfn[x]也包括dfn[y]
if (x == fa) ++subtree; //如果自己是根那么起码有一颗子树
else if (low[y] >= dfn[x]) vis[x] = 1;
//当当前节点非根且子树能达到的dfn最小的结点的时间>=自己的时间时,当前节点便是割点
} else if (y != fa)
low[x] = min(low[x], dfn[y]); //x能回溯到y
}
if (x == fa && subtree >= 2) vis[x] = 1;
//如果一个点是根节点且有两棵或以上的子树,那么这个点也是割点
}
int main() {
memset(last, -1, sizeof last);
n = read(), m = read();
for (int i = 1; i <= m; ++i)
add(0, 0);
for (int i = 1; i <= n; ++i)
if (!dfn[i]) Tarjan(i, i); //每一个联通块都要跑一遍Tarjan
int ans = 0;
for (int i = 1; i <= n; ++i)
ans += vis[i]; //统计割点个数
printf("%d\n", ans);
for (int i = 1; i <= n; ++i)
if (vis[i])
printf("%d%c", i, i == n ? '\n' : ' '); //输出
}