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
给定条件:
1.n个节点
2.n-1条连线
题目要求:
1.判断给定的图是否连通的
2.如果连通,求出选取那些节点作为根节点,所建成的树的深度最大
3.按照编号从小到大的顺序,输出符合条件的根节点
解决方法:
1.dfs求图的连通分量,判断是否为1
2.分别选取所有的节点作为根节点,进行深度优先遍历,记录所到达的最大深度,并且在搜索过程中记录每个节点所能处于的最大深度
3.遍历所有节点,输出所在深度可以为最大深度的节点
#include<cstdio>
#include<vector>
using namespace std;
int N, a, b, maxd = -1;
int vis[10001];
int depth[10001];
vector<int> e[10001];
void dfs(int v, int d){
vis[v] = 1;
depth[v] = max(depth[v], d); // update node's depth
maxd = max(maxd, d); // update the max depth
for(int i = 0; i < e[v].size(); i++){
int next = e[v][i];
if(!vis[next]){
dfs(next,d+1);
}
}
}
int main(){
while(scanf("%d", &N) != EOF){
// input
for(int i = 1; i < N; i++){
scanf("%d%d", &a, &b);
e[a].push_back(b);
e[b].push_back(a);
}
fill(vis, vis+10001, 0);
int cnt = 0;
for(int i = 1; i <= N; i++){
if(!vis[i]){
dfs(i,1);
cnt++; // the number of components
}
}
if(cnt != 1){
printf("Error: %d components\n",cnt);
}else{
// dfs every node
for(int i = 1; i <= N; i++){
fill(vis, vis+10001, 0);
vis[i] = 1;
dfs(i,1);
}
// find the node which depth is maxd
for(int i = 1; i <=N; i++){
if(depth[i] == maxd){
printf("%d\n", i);
}
}
}
}
return 0;
}