【PAT】A-1021 Deepest Root【树】【树的深度】【DFS】

该博客讨论了PAT甲级考试中的一道题,涉及树的深度和深度优先搜索(DFS)。博主首先介绍了输入和输出规格,接着展示了样例输入和输出。题目要求找到能构成最高树的根节点,如果存在多个,按节点编号升序输出。博主通过两次DFS,首次确定连通组件并找出最深节点,第二次以最深节点为根重新搜索,以确定最深树。当连通组件超过1时,输出错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N-1 lines follow, each describes an edge by given the two adjacent nodes’ numbers.

Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print “Error: K components” where K is the number of connected components in the graph.

Sample Input 1:

5
1 2
1 3
1 4
2 5

Sample Output 1:

3
4
5

Sample Input 2:

5
1 3
1 4
2 5
3 4

Sample Output 2:

Error: 2 components

题目大意

给出n个结点(1~n)之间的n条边,问是否能构成一棵树,如果不能构成则输出它有的连通分量个数,如果能构成一棵树,输出能构成最深的树的高度时,树的根结点。如果有多个,按照从小到大输出。

思路

进行两次深度优先搜索,第一次任取一个结点作为根结点(为了方便起见选择1号作为根结点),将这一次遍历中最深的结点(可能不止一个)加入到向量depthestNodes中,同时计算连通分量。

  • 若连通分量大于1,则输出Error: x components。
  • 否则执行第二次深度优先搜索,根结点为上一轮depthestNodes中的任意一个(为了方便取第一个)。

代码

#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#define maxN 10001
using namespace std;
bool marked[maxN];
vector<int> graph[maxN];
int maxHeight = 0;
vector<int> depthestNodes;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值