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 <iostream>
#include <map>
#include <vector>
#include <set>
#include <cstdio>
#include <algorithm>
using namespace std;
map <int, vector<int> > tree;
vector<int> visited;
set<int> furthest_node;
int max_dis=0;
void dfs(int node,int dis);
int main()
{
int num_node;
cin >>num_node;
for(int i=1;i<num_node;i++)
{
int a,b;
cin >>a >>b;
tree[a].push_back(b);
tree[b].push_back(a);
visited.push_back(0);
}
for(int i=0;i<=num_node+1;i++)
visited.push_back(0);
int k=0;
for(int i=1;i<=num_node;i++)
{
if(visited[i]!=1)
{
visited[i]=1;
furthest_node.insert(i);//需要加入,防止输入仅有一个节点的情况的出现;
dfs(i,0);
k++;
}
}
for(int i=0;i<=num_node+1;i++)
visited[i]=0;
max_dis=0;
set<int> record=furthest_node;
if(k==1)
{
int a=*furthest_node.begin();
visited[a]=1;
dfs(a,0);
set<int>::iterator iter=record.begin();
for(;iter!=record.end();iter++)
furthest_node.insert(*iter);
for(iter=furthest_node.begin();iter!=furthest_node.end();iter++)
cout <<*iter<<endl;
}
else
cout <<"Error: "<<k<<" components"<<endl;
return 0;
}
void dfs(int node,int dis)
{
vector<int>::iterator iter=tree[node].begin();
for(;iter!=tree[node].end();iter++)
{
int tmp=*iter;
if(visited[tmp]!=1)
{
if(dis+1>max_dis)
{
max_dis=dis+1;
furthest_node.clear();
furthest_node.insert(tmp);
}
else if(dis+1==max_dis)
furthest_node.insert(tmp);
visited[tmp]=1;
dfs(tmp,dis+1);
}
}
}