牛客多校第二场 C-Cover the Tree(dfs序)

题意

给定一颗无根树,任意两点可形成一条链,找出最少的链使其并集为全部的边。输出最少点对数并写出点对

  1. 链接Cover the Tree
  2. 范围:1≤n≤2×105 1≤u<v≤n
  3. 输入

5
1 2
1 3
2 4
2 5

  1. 输出

2
2 3
4 5

解题思路

  • 简单思路:以度不为1的点作为根节点,每次将其与叶子结点链接,即可把所有边覆盖,答案即为度为1的叶子结点数,显然不是题目所要求的最小解
  • 优化:将根节点作为中间结点,链接左右两端的根结点,则答案为(叶子节点数+1)/2 向下取整在这里插入图片描述

代码

#include<stdio.h>
int const N=2e5+5;
int n,u,v,d[N],head[N],ans[N],root,cnt,tot;
struct node{
	int to,next;
}e[N*2];
void add(int u,int v)
{
	e[++cnt].to=v;
	e[cnt].next=head[u];
	head[u]=cnt;
	d[u]++;
}
void dfs(int son,int fa)
{
	if(d[son]==1) ans[++tot]=son;
	for(int i=head[son];i;i=e[i].next)
	{
		if(e[i].to==fa)continue;
		dfs(e[i].to,son);
	} 
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<n;i++)
	{
		scanf("%d%d",&u,&v);
		add(u,v);add(v,u);
	}
	if(n==1) printf("0\n");
	else if(n==2) printf("1\n1 2\n");//特判 
	else{
		for(int i=1;i<=n;i++)
		{
			if(d[i]!=1)
			{
				root=i;break;
			}
		}
		//找任意非叶子结点作为根节点 
		dfs(root,root);
		int sum=(tot+1)/2;
		printf("%d\n",sum);
		if(tot%2==1) ans[++tot]=root;
		for(int i=1;i<=sum;i++)
			printf("%d %d\n",ans[i],ans[i+sum]);
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值