PAT 1021. Deepest Root
PAT 1021. Deepest Root
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
分析
本题用了链接表来建图,首先深度优先搜索判断它有几个连通分量。如果有多个,那就输出Error: x components,如果只有一个,就两次深度优先搜索,先从一个结点dfs后保留最高高度拥有的结点们,然后从这些结点中的其中任意一个开始dfs得到最高高度的结点们,这两个结点集合的并集就是所求
代码如下
#include<iostream>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
vector<int> temp,visited(10001,0);
vector<vector<int>> G;
set<int> result;
int n,maxheight=-1;
void dfs(int root,int height){
visited[root]=1;
if(height>maxheight){
maxheight=height;
temp.clear();
temp.push_back(root);
}else if(height==maxheight)
temp.push_back(root);
for(int i=0;i<G[root].size();i++)
if(visited[G[root][i]]==0)
dfs(G[root][i],height+1);
}
int main(){
int node1,node2,cnt=0;
cin>>n;
G.resize(n+1);
for(int i=0;i<n-1;i++){
scanf("%d%d",&node1,&node2);
G[node1].push_back(node2);
G[node2].push_back(node1);
}
for(int i=1;i<=n;i++)
if(visited[i]==0){
dfs(i,1);
cnt++;
}
for(int i=0;i<temp.size();i++)
result.insert(temp[i]);
temp.clear(); fill(visited.begin(),visited.end(),0);
if(cnt>=2) printf("Error: %d components",cnt);
else{
dfs(temp[0],1);
for(int i=0;i<temp.size();i++)
result.insert(temp[i]);
for(auto it=result.begin();it!=result.end();it++)
cout<<*it<<endl;
}
return 0;
}