题目连接:https://www.patest.cn/contests/pat-a-practise/1021
原题如下:
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 (<=10000) 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 5Sample Output 1:
3 4 5Sample Input 2:
5 1 3 1 4 2 5 3 4Sample Output 2:
Error: 2 components
这道题和1013很像,1013是求出连通集的个数即可,这道题不仅得利用连通集个数,还得求最大深度。
我一开始想的有点乱,尤其是求最大深度这块。其实这块代码的和求树的高度类似……(还是递归学得不扎实啊)。因为参考了别人的代码,图的存储用vector,
其实用数组也行。
另外,题中的条件“有N个点,N-1条边”也很有用 -> 如果树中有环,一定会ERROR
总之,太乱了……后面有时间觉得还是再写一遍吧。
1 #include<iostream> 2 #include<vector> 3 #include<string.h> 4 #include<stdio.h> 5 #define MAXN 10005 6 using namespace std; 7 vector<int>Edge[MAXN]; 8 int deep[MAXN],visited[MAXN]={0}; 9 int N; 10 11 int DFS(int v) 12 { 13 14 int i,tmp=0,Maxtmp=0; 15 visited[v]=1; 16 for (i=0;i<Edge[v].size();i++) 17 { 18 if (!visited[Edge[v][i]])tmp=DFS(Edge[v][i]); 19 20 if (tmp>Maxtmp)Maxtmp=tmp; 21 } 22 return Maxtmp+1; 23 } 24 25 int main() 26 { 27 scanf("%d",&N); 28 int v,w,i,j; 29 for (i=0;i<N-1;i++) 30 {scanf("%d %d",&v,&w); 31 Edge[v].push_back(w); 32 Edge[w].push_back(v); 33 } 34 35 memset(deep,0,sizeof(deep)); 36 37 int tag=0,Maxdeep=0; 38 39 for (i=1;i<=N;i++) 40 { 41 if(tag==0){memset(visited,0,sizeof(visited)); 42 deep[i]=DFS(i); 43 Maxdeep=Maxdeep>deep[i]?Maxdeep:deep[i];} 44 45 for (j=1;j<=N;j++) 46 { 47 if (!visited[j]) 48 { 49 tag++; 50 i=j-1; 51 break; 52 } 53 } 54 } 55 56 if (tag>0) 57 { 58 printf("Error: %d components",tag+1); 59 } 60 else 61 { 62 for (i=1;i<=N;i++) 63 { 64 if (deep[i]==Maxdeep)printf("%d ",i); 65 } 66 } 67 return 0; 68 }