//pat A1021 Deepest Root (25 分)
//先确定连通分量个数;对一个完整的连通分量,统计从各结点出发的最大深度
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn=10010;
vector<int> Adj[maxn];
vector<int> res;//存放结果根结点
bool vis[maxn]={false};
int n,depth,maxDepth=0;
void DFS(int s,int d){
vis[s]=true;
for(int i=0;i<Adj[s].size();i++){
int u=Adj[s][i];
if(vis[u]==false){
DFS(u,d+1);
}
}
depth=max(d,depth);
}
int main(){
scanf("%d",&n);
int u,v;
for(int i=0;i<n-1;i++){
scanf("%d%d",&u,&v);
Adj[u].push_back(v);
Adj[v].push_back(u);
}
int block=0;//ans连通块数
for(int i=1;i<=n;i++){
if(vis[i]==false){
DFS(i,1);
block++;
}
}
if(block>1){
printf("Error: %d components",block);
}
else{
for(int i=1;i<=n;i++){
fill(vis,vis+maxn,false);
depth=0;
DFS(i,1);//得到以i为根结点深搜的最大深度
if(depth>maxDepth){
maxDepth=depth;
res.clear();
res.push_back(i);
}
else if(depth==maxDepth){
res.push_back(i);
}
}
for(int i=0;i<res.size();i++){
printf("%d\n",res[i]);
}
}
return 0;
}
A graph which is connected and acyclic can be considered a tree. The hight 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
作者: CHEN, Yue
单位: 浙江大学
时间限制: 2000 ms
内存限制: 64 MB