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 (≤) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N1 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

题意:
判断是否为一棵树,若不是,则输出连通分量个数;若是,则输出构成树最深高度时,树的根结点。
思路:
最深高度时树的根结点,其实就是找树中的最远距离路径上的起点和终点,因此需要先进行一遍dfs找到最远距离的n个起点,再从这些起点中任选一个dfs,找到最远距离的n个终点,起点和终点都是所求点。
那为什么第一次dfs找到的点就可以当作起点呢?可以用反证法,若选其他点做起点,它所在的深度不是最大,再利用例一的图进行dfs,发现不符合题意(可以多模拟几遍进行理解)。

AC代码(参考柳神的代码

#include<iostream> #include<algorithm> #include<cstdio> #include<cstdlib> #include<vector> #include<set> #include<cmath> #include<cstring> #include<queue> #include<string.h> using namespace std; typedef long long ll; const int maxn=10010; vector<vector<int> > ve;//存储边 int vis[maxn]; vector<int> temp;//存储每一次遍历的根节点 set<int> s;//存储根节点 int n; int maxdep=0; void dfs(int node,int depth) { if(depth>maxdep) { maxdep=depth; temp.clear();//深度增加,则temp中存的已经不是最远的结点,需要清空 temp.push_back(node); } else if(depth==maxdep) { temp.push_back(node); } vis[node]=1; for(int i=0; i<ve[node].size(); i++) { if(vis[ve[node][i]]==0) {//注意是ve[node][i]不是i dfs(ve[node][i],depth+1); } } } int main() { int a,b; scanf("%d",&n); ve.resize(n+1); fill(vis,vis+maxn,0); for(int i=1; i<n; i++) { scanf("%d %d",&a,&b); ve[a].push_back(b); ve[b].push_back(a); } int cnt=0; int s1; for(int i=1; i<=n; i++) { if(vis[i]==0) { dfs(i,1); if(i==1) { if(!temp.empty()) { s1=temp[0]; for(int i=0; i<temp.size(); i++) { s.insert(temp[i]); } } } cnt++; } } if(cnt>1) { printf("Error: %d components ",cnt); } else {//从第一遍dfs的根结点中任选一个,再次dfs(可以画图模拟一下) fill(vis,vis+maxn,0); maxdep=0; temp.clear(); dfs(s1,1); for(int i=0; i<temp.size(); i++) { s.insert(temp[i]); } for(set<int>::iterator it=s.begin(); it!=s.end(); it++) { printf("%d ",*it); } } return 0; }
原文地址:https://www.cnblogs.com/dreamzj/p/14327465.html