题目描述
传送门
题意:同POJ1655,可能有多种方案,按从小到大输出。
题解
代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int max_n=5e4+5;
const int max_e=max_n*2;
const int INF=2e9;
int T,n,ans=INF,x,y,num;
int tot,point[max_n],next[max_e],v[max_e],size[max_n],ansp[max_n];
inline void add(int x,int y){++tot;next[tot]=point[x];point[x]=tot;v[tot]=y;}
inline void dfs(int x,int fa){
size[x]=1; int ansnow=0,ansnowp=0;
for (int i=point[x];i;i=next[i])
if (v[i]!=fa){
dfs(v[i],x);
size[x]+=size[v[i]];
if (size[v[i]]>ansnow){
ansnow=size[v[i]];
ansnowp=x;
}
}
if (n-size[x]>ansnow) ansnow=n-size[x],ansnowp=x;
if (ansnow<ans) ans=ansnow,ansp[num=1]=ansnowp;
else if (ansnow==ans) ansp[++num]=ansnowp;
}
int main(){
scanf("%d",&n);
for (int i=1;i<n;++i) scanf("%d%d",&x,&y),add(x,y),add(y,x);
dfs(1,0);
sort(ansp+1,ansp+num+1);
for (int i=1;i<=num;++i) printf("%d%c",ansp[i]," \n"[i==num]);
}