洛谷P3388

Gong Jin Lv6

手打代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int cut[N],root;
int dfn[N],low[N],tot;
int n,m,ans;
vector<int>G[N];

void tarjin(int x){
dfn[x]=low[x]=++tot;
int child=0;
for(int y : G[x]){
if(!dfn[y]){
tarjin(y);
low[x]=min(low[x],low[y]);
if(low[y]>=dfn[x]){
child++;
if(x!=root||child>1){
if(!cut[x])ans++;
cut[x]=true;
}
}
}
else low[x]=min(low[x],dfn[y]);
}
}

int main(){
int u,v;
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=1;i<=n;i++)if(!dfn[i])root=i,tarjin(i);
cout<<ans<<endl;
for(int i=1;i<=n;i++){
if(cut[i])cout<<i<<" ";
}
return 0;
}

AI分析

求无向图的割点。Tarjan 算法中,若某个儿子节点的 low 值不小于当前节点的 dfn 值,说明删掉当前节点后这棵子树会与外部断开,因此当前节点是割点。对于根节点则有额外条件:至少要有两个满足上述条件的儿子,因为根节点本身没有父边,只有一个儿子时删掉它不会增加连通块数量。代码用 child 计数,最后输出割点总数与所有割点编号。建图时是无向边,搜索时不能沿父边回走,这里直接用 dfn 判断即可,避免重复访问。

另外,割点和桥的判断条件很像,桥的条件是 low 值严格大于 dfn 值。写的时候注意区分大于和大于等于,一字之差就会得到错误的答案。

  • 标题: 洛谷P3388
  • 作者: Gong Jin
  • 创建于 : 2025-07-18 11:03:58
  • 更新于 : 2026-11-22 10:13:46
  • 链接: https://blog.zymc.net/2025/07/18/洛谷/洛谷P3388/
  • 版权声明: 版权所有 © Gong Jin,禁止转载。
评论
目录
洛谷P3388