题解:只不过如果有求多个点,输出所有方案。
1 #include<cstring> 2 #include<cmath> 3 #include<iostream> 4 #include<algorithm> 5 #include<cstdio> 6 #include<vector> 7 #define N 50007 8 #define inf 1000000009 9 using namespace std; 10 11 int n,id,mnum; 12 int siz[N]; 13 int cnt,head[N],next[N*2],rea[N*2]; 14 vector<int>q; 15 16 void add(int u,int v) 17 { 18 next[++cnt]=head[u]; 19 head[u]=cnt; 20 rea[cnt]=v; 21 } 22 void dfs(int u,int fa) 23 { 24 int sum=0,msiz=-1; 25 siz[u]=1; 26 for (int i=head[u];i!=-1;i=next[i]) 27 { 28 int v=rea[i]; 29 if (v==fa) continue; 30 dfs(v,u); 31 siz[u]+=siz[v]; 32 msiz=max(msiz,siz[v]); 33 } 34 msiz=max(msiz,n-siz[u]); 35 if (msiz==mnum) q.push_back(u); 36 else 37 if (msiz<mnum) 38 { 39 mnum=msiz; 40 q.clear(); 41 q.push_back(u); 42 } 43 } 44 int main() 45 { 46 scanf("%d",&n); 47 memset(head,-1,sizeof(head)); 48 memset(siz,0,sizeof(siz)); 49 for (int i=1,x,y;i<n;i++) 50 { 51 scanf("%d%d",&x,&y); 52 add(x,y),add(y,x); 53 } 54 mnum=inf; 55 dfs(1,-1); 56 sort(q.begin(),q.end()); 57 for (int i=0;i<q.size();i++) 58 printf("%d ",q[i]); 59 }