打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
1021 Deepest Root(甲级)

1021 Deepest Root (25分)
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

#include<iostream>#include<vector>#include<memory.h>using namespace std;int n;const int maxn = 10001;vector<int>v[maxn];bool vist[maxn]{ false };int max_depth = -1;//统计以任意节点作为根的最大深度,也就是该颗树的最大深度int max_tmp = -1;//记录所有节点的最大深度,所有树中的最大深度void dfs(int root, int depth){if (max_depth < depth)//求最大深度{max_depth = depth;}vist[root] = true;for (int i = 0; i < v[root].size(); i  ){if (!vist[v[root][i]]){dfs(v[root][i], depth   1);}}}int main(){cin >> n;vector<int>count;for (int i = 0; i < n - 1; i  ){int value1, value2;cin >> value1 >> value2;v[value1].push_back(value2);v[value2].push_back(value1);}for (int i = 1; i <= n; i  ){int cnt = 0;max_depth = 0;memset(vist, false, maxn);if (i == 1)//先判断是否是联通的{for (int j = 1; j <= n; j  ){if (!vist[j]){cnt  ;dfs(j, 1);}}if (cnt >= 2){cout << "Error: " << cnt << " components";return 0;}}else{dfs(i, 1);}if (max_tmp < max_depth)//更新最大深度,并将根节点入vector{count.clear();max_tmp = max_depth;count.push_back(i);}else if (max_tmp == max_depth)//相等,根节点入vector{count.push_back(i);}}for (int i = 0; i < count.size(); i  ){cout << count[i] << endl;}}
来源:https://www.icode9.com/content-4-759901.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【动态树初探】link
罗教授对于2019年RMM第三题的解析(英文原版)
0865. Smallest Subtree with all the Deepest Nodes (M)
Flow Problem(最大流)
树链剖分
信息学竞赛-复赛常用模板总结
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服