1021. Deepest Root (25)
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 5Sample Output 1:
3 4 5Sample Input 2:
5 1 3 1 4 2 5 3 4Sample Output 2:
Error: 2 components
#include <cstdio> #include<string.h> #include<string> #include<map> #include<vector> #include<stdio.h> #include<set> #include<iostream> #include <algorithm> using namespace std; vector<int> edge[10005]; int mark[10005]={0}; int deepest=-1; int path[10005]; int p=0; int tmp; void dfs(int x,int deep) { mark[x]=1; if(deep>deepest) { deepest=deep; path[0]=x; p=1; } else if(deep==deepest) { path[p++]=x; } for(int i=0;i<edge[x].size();i++) { if(mark[edge[x][i]]==0) dfs(edge[x][i],deep+1); } } intmain() { int n; cin>>n; for(int i=1;i<n;i++) { int x,y; scanf("%d %d",&x,&y); edge[x].push_back(y); edge[y].push_back(x); } dfs(1,0); int flag=0; for(int i=1;i<=n;i++) if(mark[i]==0) {flag=1;break;} if(flag==1) { int cnt=1; for(int i=1;i<=n;i++) if(mark[i]==0) { cnt++;dfs(i,0); } printf("Error: %d components",cnt); } else { tmp=path[p-1]; set<int> S; for(int i=0;i<p;i++) S.insert(path[i]); p=0; memset(mark,0,sizeof(mark)); dfs(tmp,0); for(int i=0;i<p;i++) S.insert(path[i]); for(set<int>::iterator it=S.begin();it!=S.end();it++) { cout<<*it<<endl; } } return 0; }