「洛谷 1793」跑步

传送门


Problem

有一张 n n n 个点 m m m 条边的无向图,求出从 1 1 1 n n n 必须经过的点集。(不包括 1 1 1 n n n。)

数据范围: 3 ≤ n ≤ 2000 3\le n\le2000 3n2000 1 ≤ m ≤ 8000 1\le m\le 8000 1m8000


Solution

看到这道题的数据范围比较小,我们先说一种比较暴力的方法。

我们可以枚举每个点,删掉它之后跑 d f s dfs dfs 判断 1 1 1 n n n 是否联通,时间复杂度 O ( n 2 ) O(n^2) O(n2)

但是实际上,我们还有一种 O ( n ) O(n) O(n) 的解法。

看到 “ “ 1 1 1 n n n 必须经过的点 " " ",很容易想到用割点,但是不一定所有的割点都满足条件,因为删掉割点只是让整张图不连通,并不一定就将 1 1 1 n n n 分割开来了。

那我们以 1 1 1 为根建造 d f s dfs dfs 树,那很显然树上 1 1 1 n n n 路径上的割点才是满足条件的点。

所以我们枚举 1 1 1 n n n 路径上的所有点,判断其是否为割点即可。


Code

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 20005
using namespace std;
int n,m,t,tot,num;
int first[N],v[N],nxt[N];
int dfn[N],low[N],cnt[N],fa[N],ans[N];
void add(int x,int y){
	nxt[++t]=first[x],first[x]=t,v[t]=y;
}
void Tarjan(int x){
	dfn[x]=low[x]=++tot;
	for(int i=first[x];i;i=nxt[i]){
		int to=v[i];
		if(!dfn[to]){
			Tarjan(to),fa[to]=x;
			low[x]=min(low[x],low[to]);
		}
		else  low[x]=min(low[x],dfn[to]);
	}
}
void check(int x){
	if(x==1)  return;
	if(low[x]>=dfn[fa[x]]&&fa[x]!=1)  ans[++num]=fa[x];
	check(fa[x]);
}
int main(){
	int x,y,i;
	scanf("%d%d",&n,&m);
	for(i=1;i<=m;++i){
		scanf("%d%d",&x,&y);
		add(x,y),add(y,x);
	}
	Tarjan(1),check(n);
	printf("%d\n",num);
	sort(ans+1,ans+num+1);
	for(i=1;i<=num;++i)
		printf("%d ",ans[i]);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值