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
#include<iostream>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
vector<int> node[10010];
bool visited[10010];
vector<int> out;
void init(){
memset(visited,false,10010);
}
int maxdeep=0;
void dfs(int k,int deep,int &tmax){
if(!visited[k]){
if(tmax<deep)
tmax=deep;
visited[k]=true;
for(int i=0;i<node[k].size();i++){
dfs(node[k][i],deep+1,tmax);
}
}
}
int main(){
freopen("in.txt","r",stdin);
int n,c1,c2,components=0;
scanf("%d",&n);
for(int i=1;i<n;i++){
scanf("%d%d",&c1,&c2);
node[c1].push_back(c2);
node[c2].push_back(c1);
}
for(int i=1;i<=n;i++)
{
int t=0;
if(!visited[i]){
components++;
dfs(i,1,t);
}
}
if(components==1){
for(int i=1;i<=n;i++){
init();
int tmax=0;
dfs(i,1,tmax);
if(tmax>maxdeep){
maxdeep=tmax;
out.clear();
out.push_back(i);
}
else if(tmax==maxdeep){
out.push_back(i);
}
}
sort(out.begin(),out.end());
for(int i=0;i<out.size();i++){
printf("%d\n",out[i]);
}
}
else printf("Error: %d components",components);
return 0;
}