树的dfs找叶子节点

题目描述Given an unrooted tree, you should choose the minimum number of chains that all edges in the tree are covered by at least one chain. Print the minimum number and one solution. If there are multiple solutions, print any of them.输入描述:The first line contains one integer n~(1\leq n \leq 2\times10^5)n (1≤n≤2×10 5), denoting the size of the tree.Following {n-1}n−1 lines each contains two integers u,v~(1\leq u < v \leq n)u,v (1≤u<v≤n), denoting an edge in the tree.It's guaranteed that the given graph forms a tree.输出描述:The first line contains one integer {k}k, denoting the minimum number of chains to cover all edges.Following {k}k lines each contains two integers u,v~(1\leq u,v \leq n)u,v (1≤u,v≤n), denoting a chain you have chosen. Here {u = v}u=v is permitted, which covers no edge.示例1输入复制51 21 32 42 5输出复制22 34 5说明

在这里插入图片描述

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define N 200000 + 5

int n, m, rt, cnt, Deg[N], Leaf[N];
vector<int> Vec[N];

void dfs(int z, int fa)//fa记录上一个节点的编号,即判断是否经过
{
    if (Deg[z] == 1)
        Leaf[++ cnt] = z;
    for (int d : Vec[z])
        if (d != fa)
            dfs(d, z);
}

int main()
{
    scanf("%d", &n);
    for (int i = 1, u, v; i < n; i ++)
    {
        scanf("%d%d", &u, &v);
        Vec[u].push_back(v);
        Vec[v].push_back(u);
        Deg[u] ++, Deg[v] ++;
    }
    for (int i = 1; !rt && i <= n; i ++)/求根,第一个度大于1的节点即可当作根
        if (Deg[i] > 1)
            rt = i;
    dfs(rt, 0);
    m = (cnt + 1) / 2;
    printf("%d\n", m);
    for (int i = 1; i * 2 <= cnt; i ++)
        printf("%d %d\n", Leaf[i + m], Leaf[i]);
    if (cnt & 1)
        printf("%d %d\n", rt, Leaf[m]);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值