1021 Deepest Root (25 分)
A graph which is connected and acyclic can be considered a tree. The hight 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 (≤104) 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
#include<bits/stdc++.h>
using namespace std;
const int Max = 10010;
int n, k = 0, maxh = -1;
vector<int> node[Max];
bool is[Max] = {false};
vector<int> temp;
set<int> ans;
void dfs(int x){
is[x] = true;
for(int i = 0; i < node[x].size(); i++){
if(!is[node[x][i]])
dfs(node[x][i]);
}
}
void conn(){
for(int i = 1; i <= n; i++){
if(!is[i]){
dfs(i);
k++;
}
}
}
void deep(int x, int high, int pre){
if(high > maxh){
temp.clear();
maxh = high;
temp.push_back(x);
}
else if(high == maxh){
temp.push_back(x);
}
for(int i = 0; i < node[x].size(); i++){
if(node[x][i] == pre)
continue;
deep(node[x][i], high + 1, x);
}
}
int main(){
scanf("%d", &n);
int a, b;
for(int i = 0; i < n - 1; i++){
scanf("%d %d", &a, &b);
node[a].push_back(b);
node[b].push_back(a);
}
conn();
if(k > 1){
printf("Error: %d components", k);
return 0;
}
deep(1, 0, 0);
for(int i = 0; i < temp.size(); i++)
ans.insert(temp[i]);
maxh = -1;
a = temp[0];
temp.clear();
deep(a, 0, 0);
for(int i = 0; i < temp.size(); i++)
ans.insert(temp[i]);
for(set<int>::iterator it = ans.begin(); it != ans.end(); it++)
printf("%d\n", *it);
return 0;
}