POJ3107 (树的重心)

const maxn=50008;
      INF=2000000000;
type arr=record
        u,v,nt:longint;
        end;
     arr1=array[0..maxn] of longint;
var eg:array[0..maxn*2] of arr;
    lt:array[0..maxn] of longint;
    flag:array[0..maxn] of boolean;
    son:array[0..maxn] of longint;
    ans:array[0..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 2];
    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]:=0;
    i:=lt[u];
    tmp:=0;
    while i<>0 do
    begin
        v:=eg[i].v;
        if not flag[v] then
        begin
            dfs(v);
            son[u]:=son[u]+son[v]+1;
            if son[v]+1>tmp then tmp:=son[v]+1;
        end;    
        i:=eg[i].nt;
    end;
    if n-son[u]-1>tmp then tmp:=n-son[u]-1;
    if tmp=min then
    begin
        inc(num);
        ans[num]:=u;
    end else
    if tmp<min then
    begin
        min:=tmp;
        num:=1;
        ans[1]:=u;
    end;
end;
begin
    j:=0;
    readln(n);
    for i:=1 to n-1 do
    begin
        readln(x,y);
        add(x,y);
        add(y,x);
    end;
    min:=INF;
    dfs(1);
    sort(1,num,ans);
    for i:=1 to num do write(ans[i],' ');
end.

 

posted @ 2015-04-07 20:28  rpSebastian  阅读(141)  评论(0编辑  收藏  举报