标签:
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 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 此题需要注意的就是理论的证明。相当于在一棵树上寻找最长路径。
1 #include <iostream> 2 #include <vector> 3 #include <cstdio> 4 #include <algorithm> 5 using namespace std; 6 #define MAX 10010 7 vector<int>G[MAX]; 8 int father[MAX]; 9 bool Isfather[MAX]; 10 vector<int>temp,ans; 11 12 void Init() 13 { 14 for(int i=0;i<MAX;i++) 15 { 16 father[i]=i; 17 } 18 } 19 int FindFather(int x) 20 { 21 int z=x; 22 while(x!=father[x]) 23 { 24 x=father[x]; 25 } 26 //进行压缩 27 while(z!=father[z]) 28 { 29 int tem=father[z]; 30 father[z]=x; 31 z=tem; 32 } 33 return x; 34 } 35 void Union(int a,int b) 36 { 37 int fa=FindFather(a); 38 int fb=FindFather(b); 39 if(fa!=fb) 40 { 41 father[fa]=fb; 42 } 43 } 44 int Cal(int n) 45 { 46 int count=0; 47 for(int i=1;i<=n;i++) 48 { 49 if(father[i]==i) 50 count++; 51 } 52 return count; 53 } 54 int heightmax=0; 55 void DFS(int index,int height,int pre)//pre???? 56 { 57 if(height>heightmax) 58 { 59 temp.clear(); 60 temp.push_back(index); 61 heightmax=height; 62 }else if(height==heightmax) 63 { 64 temp.push_back(index); 65 } 66 for(int i=0;i<G[index].size();i++) 67 { 68 if(G[index][i]==pre) 69 continue; 70 DFS(G[index][i],height+1,index); 71 } 72 } 73 74 75 int main(int argc, char *argv[]) 76 { 77 int N; 78 Init(); 79 scanf("%d",&N); 80 for(int i=0;i<N-1;i++) 81 { 82 int a,b; 83 scanf("%d%d",&a,&b); 84 G[a].push_back(b); 85 G[b].push_back(a); 86 Union(a,b); 87 } 88 int block=Cal(N); 89 if(block!=1) 90 printf("Error: %d components\n",block); 91 else 92 { 93 DFS(1,1,-1); 94 ans=temp; 95 DFS(ans[0],1,-1); 96 for(int i=0;i<temp.size();i++) 97 ans.push_back(temp[i]); 98 sort(ans.begin(),ans.end()); 99 printf("%d\n",ans[0]); 100 for(int i=1;i<ans.size();i++) 101 { 102 if(ans[i-1]!=ans[i]) 103 printf("%d\n",ans[i]); 104 } 105 } 106 return 0; 107 }
标签:
原文地址:http://www.cnblogs.com/GoFly/p/4302561.html