树的重心

寻找树的重心

#include<cstdio>
#include<cstdlib>
#include<iostream>
#define N 1000004
#define inf 0x3f3f3f3f
using namespace std;

void read(int &s){
    char ch=getchar();int f=1;
    for(;!isdigit(ch);ch=getchar())if(ch='-')f=-1;
    for(s=0;isdigit(ch);s=s*10+ch-'0',ch=getchar());
    s*=f;
}

void print(int s){
    printf("%d\n",s);
    return ;
}

int n;
int siz[N];
int son[N];
int root,minl;

struct Edge{
    int v,nxt;
}e[N];
int head[N],tot;

void AddEdge(int u,int v){
    e[++tot].v=v;
    e[++tot].nxt=head[u];
    head[u]=tot;
    e[++tot].v=u;
    e[++tot].nxt=head[v];
    head[v]=tot;
}

void dfs(int node,int fa){
    for(int i=head[node];i;i=e[i].nxt){
        int to=e[i].v;
        if(to==fa)continue;
        dfs(to,node);
        siz[node]+=siz[to];
        son[node]=max(son[node],siz[to]);
    }
    son[node]=max(son[node],n-son[node]-1);
    if(son[node]<minl)minl=son[node],root=node;
    return ;
}

int main(){
    int a,b;
    minl=inf;
    read(n);
    for(int i=1;i<n;++i){
        read(a),read(b);AddEdge(a,b);
    }
    dfs(1,0);
    print(root);
    system("pause");
    return 0;
}
posted @ 2018-01-02 18:08  Grary  阅读(135)  评论(0编辑  收藏  举报
博客园 首页 私信博主 编辑 关注 管理 新世界