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
whereK
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
采用dfs我们常用vector来存储图之间的关系
#include<iostream>
#include<vector>
#include<set>
using namespace std;
vector<int>v[10001];
int visited[10001],maxdis=0;
set<int>final_ans;
vector<int>farthest_point;
//dfs常用两个数组,vector来存放关系,visited来表示是否遍历过,再用若干个数组来存放数组
void dfs(int cur){
if(visited[cur])return;
visited[cur]=1;
for(int i:v[cur]){
dfs(i);
}
}
void dfs2(int cur,int depth){
if(visited[cur])return;//及时止损
visited[cur]=1;
if(depth>maxdis){
//现在的深度比最大深度还大,就更新maxdis
maxdis=depth;
farthest_point.clear();
farthest_point.emplace_back(cur);//更新最远结点的值
}
else if(depth=maxdis){
farthest_point.emplace_back(cur);//到达最大结点也记录该最远结点
}
for(int i:v[cur]){
//继续遍历i的邻居结点
dfs2(i,depth+1);
}
}
int main(){
int N,i,j,k;
cin>>N;
for(i=1;i<N;i++){
cin>>j>>k;
v[j].emplace_back(k);
v[k].emplace_back(j);
}
//输入
for(i=0;i<=N;i++)visited[i]=0;
int count=0;
for(i=1;i<=N;i++){
//计算连通子图的方式
if(!visited[i]){
count++;
dfs(i);
}
}
//不是树
if(count>1){
cout<<"Error: "<<count<<" components";
}
//是树
else{
for(i=1;i<=N;i++)visited[i]=0;
dfs2(1,0);//随便在主链上找一个位置,e.g:从位置1开始dfs,深度为0
for(int each:farthest_point)final_ans.insert(each);//将最远结点存放在final_ans里面 ,作为新起点
//从新起点找到另一侧的最远根结点
for(i=1;i<=N;i++)visited[i]=0;
farthest_point.clear();
maxdis=0;
dfs2(*final_ans.begin(),0);
for(int each:farthest_point)final_ans.insert(each);
for(int each:final_ans){
cout<<each<<'\n';
}
}
}