Pat【甲级】 1021 Deepest Root(附中文题目)

Deepest Root

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 (≤10
​4
​​ ) 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 行,每行包含两个整数,表示两个节点之间存在一条边。

输出格式
输出最深的根的节点编号。

如果最深的根不唯一,则按照从小到大的顺序,将它们依次输出,每个占一行。

如果给定的图不是树,输出 Error: K components,其中 K 是图中连通分量的数量。

数据范围
1≤N≤104
输入样例1:

5
1 2
1 3
1 4
2 5

输出样例1:

3
4
5

输入样例2:

5
1 3
1 4
2 5
3 4

输出样例2:

Error: 2 components

说明:首先我们先要判断是否只有一个连通分量(在这我们用并查集来判断是最快的也是最好写的),接下来我们看数据范围比较小那么我们判断根的深度直接用枚举然后dfs判断根的深度就好了

代码

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 10010;
int p[N];
int n;
vector<int>vv[N];
//并查集的查找函数+缩短路径
int find(int x) {
	if (p[x] != x)p[x] = find(p[x]);
	return p[x];
}

//判断深度
int dfs(int u, int father) {
	int depth = 1;
	for (int i = 0; i < vv[u].size(); i++) {
		if (vv[u][i] != father) {
			depth = max(depth, dfs(vv[u][i], u)+1);
		}
	}
	return depth;
}

int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		p[i] = i;
	}
	int t = n;
	for (int i = 0; i < n-1; i++) {
		int a, b;
		cin >> a >> b;
		//利用并查集来判断连通分量
		if (find(a) != find(b)) {
			t--;
			p[find(a)] = find(b);
		}
		vv[a].push_back(b);
		vv[b].push_back(a);
	}
	if (t > 1) {
		cout << "Error: " << t << " components" << endl;
	}
	else {
		vector<int>vv1;
		int max_depth = -1;
		for (int i = 1; i <= n; i++) {
			int depth = dfs(i, -1);
			if (depth > max_depth) {
				vv1.clear();
				vv1.push_back(i);
				max_depth = depth;
			}
			else if (depth == max_depth) {
				vv1.push_back(i);
			}
		}
		for (int i = 0; i < vv1.size(); i++) {
			cout << vv1[i] << endl;
		}
	}

	

	return 0;
}

运行结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值