POJ3107 (树的重心)

时间:2022-07-14 18:32:27
const maxn=;
INF=;
type arr=record
u,v,nt:longint;
end;
arr1=array[..maxn] of longint;
var eg:array[..maxn*] of arr;
lt:array[..maxn] of longint;
flag:array[..maxn] of boolean;
son:array[..maxn] of longint;
ans:array[..maxn] of longint;
min,x,y,n,i,j,num:longint;
procedure swap(var a,b:longint);
var c:longint;
begin
c:=a; a:=b; b:=c;
end;
procedure sort(l,r:longint;var a:arr1);
var i,j,x:longint;
begin
i:=l; j:=r; x:=a[(i+j) div ];
while i<=j do
begin
while a[i]<x do inc(i);
while x<a[j] do dec(j);
if i<=j then
begin
swap(a[i],a[j]);
inc(i);
dec(j);
end;
end;
if l<j then sort(l,j,a);
if i<r then sort(i,r,a);
end;
procedure add(u,v:longint);
begin
inc(j);
eg[j].u:=u;
eg[j].v:=v;
eg[j].nt:=lt[u];
lt[u]:=j;
end;
procedure dfs(u:longint);
var i,v,tmp:longint;
begin
flag[u]:=true;
son[u]:=;
i:=lt[u];
tmp:=;
while i<> do
begin
v:=eg[i].v;
if not flag[v] then
begin
dfs(v);
son[u]:=son[u]+son[v]+;
if son[v]+>tmp then tmp:=son[v]+;
end;
i:=eg[i].nt;
end;
if n-son[u]->tmp then tmp:=n-son[u]-;
if tmp=min then
begin
inc(num);
ans[num]:=u;
end else
if tmp<min then
begin
min:=tmp;
num:=;
ans[]:=u;
end;
end;
begin
j:=;
readln(n);
for i:= to n- do
begin
readln(x,y);
add(x,y);
add(y,x);
end;
min:=INF;
dfs();
sort(,num,ans);
for i:= to num do write(ans[i],' ');
end.