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
题目大意:给出n个点和n-1条边,问是否能形成一个n个节点的树,如果能从中选出节点作为树根,使得整棵树高度最大,输出所有满足要求的根。如果不能,输出有多少个连通块。
思路:遍历每个节点,通过DFS算出该节点作为根节点时最大高度是多少,存在dep[maxx]数组中,比如按题中数据1,可得到dep[1]=2,dep[2]=2,dep[3]=3,dep[4]=3,dep[5]=3,然后得到数组中最大值,最后得到对应序号。
刚开始没有看到第二个数据,后面发现有个测试点不能通过才注意到,对于不止一个连通块,我们可以用a1013的思路,DFS遍历,得到连通块数目:
(18条消息) a1013 Battle Over Cities (图的遍历 DFS)_adoge_的博客-CSDN博客
#include <iostream>
#include "vector"
#include "algorithm"
using namespace std;
const int maxx = 11000;
int maxdepth,n,dep[maxx];
bool vis[maxx];
vector<int> G[maxx];
int DFS(int u,int depth){
vis[u] = true;
if (depth > maxdepth) maxdepth = depth;
for (int i = 0; i < G[u].size(); ++i) {
if (!vis[G[u][i]]){
DFS(G[u][i],depth+1);
}
}
return maxdepth;
}
int main() {
cin>>n;
int a,b;
for (int i = 0; i < n-1; ++i) {
cin>>a>>b;
G[a].push_back(b);
G[b].push_back(a);
}
for (int i = 1; i <= n; ++i) {
fill(vis,vis+maxx, false);
maxdepth=0;
dep[i]=DFS(i,0);
}
int blocks=0;
fill(vis,vis+maxx, false);
for (int j = 1; j <= n; ++j) {
if (!vis[j]){
DFS(j,0);
blocks++;
}
}
if (blocks==1){
int ans = *max_element(dep + 1, dep + n);
for (int i = 1; i <= n; ++i) {
if (dep[i] == ans) cout << i << endl;
}
} else{
printf("Error: %d components\n",blocks);
}
}