P3388 【模板】割点(割顶)(tarjan求割点)

【模板】割点(割顶)

题目背景

割点

题目描述

给出一个 \(n\) 个点,\(m\) 条边的无向图,求图的割点。

输入格式

第一行输入两个正整数 \(n,m\)

下面 \(m\) 行每行输入两个正整数 \(x,y\) 表示 \(x\)\(y\) 有一条边。

输出格式

第一行输出割点个数。

第二行按照节点编号从小到大输出节点,用空格隔开。

样例 #1

样例输入 #1

6 7
1 2
1 3
1 4
2 5
3 5
4 5
5 6

样例输出 #1

1 
5

提示

对于全部数据,\(1\leq n \le 2\times 10^4\)\(1\leq m \le 1 \times 10^5\)

点的编号均大于 \(0\) 小于等于 \(n\)

tarjan图不一定联通。

代码

// Problem: P3388 【模板】割点(割顶)
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3388
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// Created Time: 2022-07-20 23:16:20
// 
// Powered by CP Editor (https://cpeditor.org)

//fw
#include<iostream>
#include<cstdio>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<deque>
#include<vector>
#include<queue>
#include<string>
#include<cstring>
#include<map>
#include<stack>
#include<set>
#include<climits>
#define zp ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
#define pii pair <int, int>
#define endl '\n'
#define pb push_back
#define lc u<<1
#define rc u<<1|1
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const int N=1e5+10,M=2e5+5;
int h[N],e[M],ne[M],idx,n,m;
int dfn[N],low[N],times;
bool is_cut[N];
int root;
void add(int a,int b)
{
	e[idx]=b;
	ne[idx]=h[a];
	h[a]=idx++;
}
void tarjan(int u)
{
	dfn[u]=low[u]=++times;//记录时间戳

	int cnt=0;//对满足low[j]>=dfn[y]的子节点计数

	for(int i=h[u];~i;i=ne[i])
	{
		int j=e[i];
		if(!dfn[j])//如果没有访问过
		{
			tarjan(j);//访问

			low[u]=min(low[u],low[j]);//更新

			if(low[j]>=dfn[u])//如果满足条件,即从该节点不能在不经过u的情况下到达更早的节点
			{
				cnt++;//计数
				if(u!=root||cnt>1)//如果不是根,满足一次条件即可判为割点,否则至少需要两次以上
					is_cut[u]=true;
			}
		}
		else
			low[u]=min(low[u],dfn[j]);//已经访问过则更新,有可能是dfn更小的点
	}
}
int main()
{
	//建图
    memset(h,-1,sizeof h);
    cin>>n>>m;
    while(m--)
    {
    	int a,b;
    	cin>>a>>b;
    	add(a,b);
    	add(b,a);
    }

	//求割点
    for(root=1;root<=n;root++)
    	if(!dfn[root])
    		tarjan(root);
    
	//输出答案
    int ans=0;
    for(int i=1;i<=n;i++)
    	if(is_cut[i])
    		ans++;
    cout<<ans<<endl;
    
    for(int i=1;i<=n;i++)
    	if(is_cut[i])
    		cout<<i<<" ";
    return 0;
}
posted @ 2022-07-21 11:04  Avarice_Zhao  阅读(50)  评论(0编辑  收藏  举报