[poj3107]Godfather

求树的重心

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <cstdlib>
 6 #include <queue>
 7 #include <string>
 8 #include <vector>
 9 using namespace std;
10 
11 const int N=100100;
12 int n,h[N],r[N],to[N],tot,root,sz[N],f[N];
13 
14 void add(int u,int v){
15     to[tot]=v;
16     r[tot]=h[u];
17     h[u]=tot++;
18 }
19 
20 void getRoot(int x,int fa){
21     sz[x]=1;
22     f[x]=0;
23     for(int i=h[x];i!=-1;i=r[i]){
24         if(to[i]!=fa){
25             getRoot(to[i],x);
26             sz[x]+=sz[to[i]];
27             f[x]=max(f[x],sz[to[i]]);
28         }
29     }
30     f[x]=max(f[x],n-sz[x]);
31     if(f[x]<f[root])root=x;
32 }
33 
34 
35 int main(){
36     memset(h,-1,sizeof(h));
37     scanf("%d",&n);
38     for(int i=1,u,v;i<n;i++){
39         scanf("%d%d",&u,&v);
40         add(u,v);
41         add(v,u);
42     }
43     f[0]=0x3f3f3f3f;
44     getRoot(1,0);
45     for(int i=1;i<=n;i++)
46         if(f[i]==f[root])
47             printf("%d ",i);
48 }
View Code

 

posted @ 2017-01-25 17:56  KingSann  阅读(100)  评论(0编辑  收藏  举报