树的重心

const int N = 50005;  
const int INF = 1<<30;  
  
int head[N];  
int son[N];  
bool vis[N];  
int cnt,n;  
int num,size;  
int ans[N];  
  
struct Edge  
{  
    int to;  
    int next;  
};  
  
Edge edge[2*N];  
  
void Init()  
{  
    cnt = 0;  
    num = 0;  
    size = INF;  
    memset(vis,0,sizeof(vis));  
    memset(head,-1,sizeof(head));  
}  
  
void add(int u,int v)  
{  
    edge[cnt].to = v;  
    edge[cnt].next = head[u];  
    head[u] = cnt++;  
}  
  
void dfs(int cur)  
{  
    vis[cur] = 1;  
    son[cur] = 0;  
    int tmp = 0;  
    for(int i=head[cur];~i;i=edge[i].next)  
    {  
        int u = edge[i].to;  
        if(!vis[u])  
        {  
            dfs(u);  
            son[cur] += son[u] + 1;  
            tmp = max(tmp,son[u] + 1);  
        }  
    }  
    tmp = max(tmp,n-son[cur]-1);  
    if(tmp < size)  
    {  
        num = 1;  
        ans[0] = cur;  
        size = tmp;  
    }  
    else if(tmp == size)  
    {  
        ans[num++] = cur;  
    }  
}  
  
int main()  
{  
    while(~scanf("%d",&n))  
    {  
        Init();  
        for(int i=1;i<=n-1;i++)  
        {  
            int u,v;  
            scanf("%d%d",&u,&v);  
            add(u,v);  
            add(v,u);  
        }  
        dfs(1);  
        sort(ans,ans+num);  
        for(int i=0;i<num;i++)  
            printf("%d ",ans[i]);  
        puts("");  
    }  
    return 0;  
}  

 

posted on 2017-04-20 17:18  very_czy  阅读(164)  评论(0编辑  收藏  举报

导航