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
题目大意:
一个连通的无环图可以被看作是一棵树。树的高度取决于被选中作为根的顶点,现要求你找到可以让这棵树最高的顶点并输出。如给出的图不能构成一棵树,那么输出Error: ... components,如有多个满足条件的顶点,那么升序将它们输出。
解题思路:
最初的想法是利用邻接矩阵存储图,首先dfs判断该图是否为连通图(连通分量为1),不连通则直接Error,之后再重新从每个顶点开始进行一遍深度遍历,找到深度最大的顶点并存储下来升序输出。这样做的后果就是先出现内存超出限制(邻接矩阵导致),然后测试点3超时(N遍dfs导致)🤧。
解决办法:
- 邻接表存储图
- 首先dfs计算连通分量,在该过程中利用set存储能够到达的最深的叶子结点;可以知道,如果要找到最长的一条路,必然是要到达叶子结点的,因此再从之前set存储的叶子结点中任意取出一个,再进行一次dfs遍历,将其可到达的最深的点存储在一个新的set集合中,将两个集合合并即为最深的根节点。
- set非常好用,可以自动排序+过滤重复的点
参考博客https://blog.csdn.net/zhang35/article/details/104198822
代码如下:
#include<iostream>
#include<set>
#include<vector>
using namespace std;
int n,sum = 0;
vector<int> arcs[10001];
bool visited[10001];
set<int> ans,temp;
int MAX = 0;
void dfs(int u,int length){
visited[u] = true;
if(length > MAX){
ans.clear();
ans.insert(u);
MAX = length;
}else if(length == MAX)
ans.insert(u);
for(int i = 0; i < arcs[u].size() ; i ++){
if(!visited[arcs[u][i]])
dfs(arcs[u][i],length+1);
}
}
int main(){
fill(visited,visited+10001,false);
scanf("%d",&n);
for(int i = 1 ; i <= n-1 ; i ++){
int a,b;
scanf("%d%d",&a,&b);
arcs[a].push_back(b);
arcs[b].push_back(a);
}
for(int i = 1 ; i <= n ; i ++){
if(!visited[i]){
dfs(i,1);
sum ++;
}
}
if(sum > 1)
printf("Error: %d components",sum);
else{
fill(visited,visited+10001,false);
temp = ans;
ans.clear();
dfs(*temp.begin(),1);
for(set<int>::iterator i = temp.begin(); i != temp.end() ; ++i)
ans.insert(*i);
for(set<int>::iterator it = ans.begin(); it != ans.end(); ++it)
printf("%d\n",*it);
}
return 0;
}