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 (<=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个顶点,给出N-1条边,而且题目强烈的暗示了针对每一个顶点都有一条对应边存在,所以不需要考虑环存在的问题(否则稍微麻烦一些)!然后对于连通分量求算,对于邻接链表逐个进行深搜然后确定即可;对于最大树高度的求算时候,每次深搜过程中保留从出发点计算的当前高度,然后设置全局变量-最大高度,逐个更新即可;参考的柳神的博客,里面解释的非常清楚,然后自己贴上自己实现的代码;
代码
#include <iostream>
#include <vector>
#include <set>
using namespace std;
bool flag[10005];
vector<vector<int>> adj;
vector<int> temp;
int maxHeight = 0;
set<int> s;
void dfs(int u, int height) {
if (height > maxHeight) {
temp.clear();
temp.push_back(u);
maxHeight = height;
}
else if (height == maxHeight) {
temp.push_back(u);
}
flag[u] = true;
for (int i=0; i<adj[u].size(); i++) {
if (!flag[adj[u][i]]) dfs(adj[u][i], height+1);
}
}
int main() {
int n;
cin >> n;
adj.resize(n + 1);
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
int cnt = 0, s1;
for (int i = 1; i <= n; i++) {
if (!flag[i]) {
dfs(i, 1);
if (i == 1) {
if (temp.size() != 0) s1 = temp[0];
for (int j = 0; j < temp.size(); j++)
s.insert(temp[j]);
}
cnt++;
}
}
if (cnt >=2) {
printf("Error: %d components", cnt);
return 0;
}
else {
temp.clear();
maxHeight = 0;
fill(flag, flag + 10005, false);
dfs(s1, 1);
for (int i = 0; i < temp.size(); i++)
s.insert(temp[i]);
for (auto it : s) {
printf("%d\n", it);
}
}
return 0;
}
总结
欣赏简练优美的代码,就像品尝美味佳酿,让人流连忘返,沉醉不已;