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 (≤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 <iostream>
#include <vector>
#include <set>
using namespace std;
#define rep(i,j,k) for(int i=j;i<k;i++)
vector<int> v[10010],index;
bool vis[10010];
int maxDep=-1;
set<int> st;
void dfs(int u,int dep){
if(dep > maxDep){
maxDep = dep;
index.clear();
index.push_back(u);
}else if(dep == maxDep){
index.push_back(u);
}
vis[u] = true;
rep(i,0,v[u].size()){
if(vis[v[u][i]] == false)
dfs(v[u][i],dep+1);
}
}
int main(){
int n,a,b,cnt=0,s1=0;
cin>>n;
rep(i,0,n-1){
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}
rep(i,1,n+1){
if(vis[i]==false){
dfs(i,1);
if(i == 1){
if(index.size() != 0){
s1 = index[0];
rep(j,0,index.size())
st.insert(index[j]);
}
}
cnt++;
}
}
if(cnt >= 2)
printf("Error: %d components",cnt);
else{
index.clear();
maxDep = 0;
fill(vis,vis+10010,false);
dfs(s1,1);
rep(i,0,index.size())
st.insert(index[i]);
for(set<int>::iterator it=st.begin();it!=st.end();it++)
printf("%d\n",*it);
}
return 0;
}