1021 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(<= 10000),它是节点的数目,因此节点的编号从1到N。然后是N-1行,每行描述一条边,给定两个 相邻节点的编号。
输出规格:
对于每个测试用例,在一行中打印每个最深的根。 如果这样的词根不是唯一的,请按数字升序打印。 如果给定的图不是树,则打印“错误:K个组件”,其中K是图中连接的组件数。
思路:
需要两次遍历,第一次遍历找到有几个连通分量,如果一个的话就是可以构成树,然后再一次遍历把树的高度排序找出不同可能存在的结点
#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 10010;
int n; //n个结点
int maxheight = 0;
vector<vector<int> > v;
set<int> s;
vector<int> temp;
bool visit[MAX_N];
int cnt = 0; //计数
int s1 = 0;
void init() {
cin >> n;
v.resize(n + 1);
int a, b;
for(int i = 0; i < n - 1; i++) {
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
}
void dfs(int node, int height) {
if(height > maxheight) {
temp.clear();
temp.push_back(node);
maxheight = height;
} else if(height == maxheight) {
temp.push_back(node);
}
visit[node] = true;
for(int i = 0; i < v[node].size(); i++) {
if(visit[v[node][i]] == false) {
dfs(v[node][i], height + 1);
}
}
}
int main() {
init();
for(int i = 1; i <= n; i++) {
//如果能构成一棵树,则一次遍历就能全遍历到
if(visit[i] == false) {
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) {
cout << "Error: " << cnt << " components";
} else {
temp.clear();
maxheight = 0;
fill(visit, visit + MAX_N, false);
dfs(s1, 1);
for(int i = 0; i < temp.size(); i++) {
s.insert(temp[i]);
}
for(auto it = s.begin(); it != s.end(); it++) {
cout << *it << endl;
}
}
return 0;
}