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 (≤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
知识点
注意点
求图中有几个连通块
并查集的应用:图中有几个连通块的问题是并查集的基础应用,设置一个变量num,这个值初始化为n,然后把所有的边都扫一遍,如果边的两点原来就在一个连通块里边,那样连上这条边以后连通块的数目也不改变,但是如果两个点原来不在一个连通块里,那么连上这两个点以后连通块的数目就要减1.
求某个节点作为根以后树的高度
这个过程其实是一个递归的调用,dfs函数的目的就是返回当前树的高度,而当前树的高度就是所有子树的高度最大值然后加一。
AC代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e4+10;
const int M=2e4+10;
int n;
int hd[N],e[M],ne[M],idx;
int p[N];
int find(int x){
if(p[x]!=x) p[x]=find(p[x]);
return p[x];
}
void add(int x,int y){
e[idx]=y,ne[idx]=hd[x],hd[x]=idx++;
}
int dfs(int u,int father){
int depth=0;
for(int i=hd[u];i!=-1;i=ne[i]){
int j=e[i];
if(j==father) continue;
depth=max(depth,dfs(j,u)+1);
}
return depth;
}
int main(){
cin>>n;
memset(hd,-1,sizeof hd);
for(int i=1;i<=n;i++) p[i]=i;
int num=n;
for(int i=1;i<n;i++){
int a,b;
cin>>a>>b;
add(a,b),add(b,a);
if(find(a)!=find(b)) num--,p[find(a)]=find(b);
}
// cout<<"num=="<<num<<endl;
if(num==1){
vector<int> nodes;
int max_depth=-1;
for(int i=1;i<=n;i++){
int depth=dfs(i,-1);
if(depth>max_depth){
max_depth=depth;
nodes.clear();
nodes.push_back(i);
}else if(depth==max_depth)
nodes.push_back(i);
}
int len=nodes.size();
for(int i=0;i<len;i++)
cout<<nodes[i]<<endl;
}else{
cout<<"Error: "<<num<<" components"<<endl;
}
return 0;
}