1021 Deepest Root (25 分)
A graph which is connected and acyclic can be considered a tree. The hight 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
思路-:
求出连通图每一个顶点所对应的最大深度,存入到一个数组中,在输出时,只需要遍历这个数组,输出和最大深度相同的结点下标为止。
思路二:
从任意一个顶点开始遍历,在这次遍历过程中,记录下深度最大的顶点小标(可能不止一个),然后从上次遍历记录下的顶点下标(其中任何一个)开始进行深度
优先遍历,把具有最大高度的顶点编号记录下来(可能不止一个),两次遍历的并集即为所求。
技巧:
使用c++中的vector构造邻接表,这样的时间复杂度是o(e+v)(顶点数和边数的和),当输入较大时,无论时间复杂度还是空间复杂度都比使用邻接矩阵要小。
#include<iostream> #include<cstdio> #include<string.h> #include<vector> #include<set> using namespace std; bool visited[10001]; int n; vector<int> temp; vector<vector<int>> v;//这样的实现是使用邻接表 set<int> s; int d=0; void dfs2(int start,int deep) { d=max(deep,d); for(int i=0; i<v[start].size(); i++) { if(visited[v[start][i]]==false) { visited[v[start][i]]=true; dfs2(v[start][i],deep+1); } } } int main() { scanf("%d",&n); v.resize(n+1); for(int i=0; i<n-1; i++) { int x,y; scanf("%d%d",&x,&y); v[x].push_back(y); v[y].push_back(x); } int num=0; int s1=1; fill(visited,visited+10001,false); for(int i=1; i<n+1; i++) { if(visited[i]==false) { num++; visited[i]=true; dfs2(i,0); } } if(num>1) { printf("Error: %d components",num); } else { int deep[n+1]; int maxValue=0; for(int i=1;i<n+1;i++) { d=0; fill(visited,visited+10001,false); visited[i]=true; dfs2(i,0); deep[i]=d; maxValue=max(d,maxValue); } for(int i=1;i<n+1;i++) if(deep[i]==maxValue) printf("%d ",i); } return 0; }