M - Godfather POJ - 树的重心

  • M - Godfather

  •  POJ - 3107 
  • 的重心也叫的质心。找到一个点,其所有的子树中最大的子树节点数最少,那么这个点就是这棵树的重心,删去重心后,生成的多棵树尽可能平衡。
  • Based on the idea that Godfather wants to have the most possible control over mafia, the chief of the police has made a suggestion that Godfather is such a person that after deleting it from the communications tree the size of the largest remaining connected component is as small as possible. Help the police to find all potential Godfathers and they will arrest them.
  • 基于教父想要对黑手党进行尽可能多的控制的想法,警察局长建议教父是这样的人,在从通信树中删除它之后,剩下的最大的连接部件的尺寸尽可能小。帮助警察找到所有潜在的教父,他们会逮捕他们。
  • #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    #define maxn 50005
    #define inf 0x3f3f3f3f
    struct node
    {
        int v,to;
    } edge[maxn*2];
    int head[maxn];
    int cnt,x,y,n;
    int dp[maxn],num;
    int ans[maxn],sum;
    void add(int u,int v)
    {
        edge[++cnt].to=head[u];
        edge[cnt].v=v;
        head[u]=cnt;
        edge[++cnt].to=head[v];
        edge[cnt].v=u;
        head[v]=cnt;
    }
    void dfs(int u,int pre)
    {
        dp[u]=1;
        int temp=0;
        for(int i=head[u]; i!=-1; i=edge[i].to)
        {
            int v=edge[i].v;
            if(v==pre)continue;
            dfs(v,u);
            dp[u]+=dp[v];
            temp=max(temp,dp[v]);
        }
        temp=max(temp,n-dp[u]);
        if(temp<sum)
        {
            sum=temp;
            num=0;
            ans[++num]=u;
        }
        else if(temp==sum)
            ans[++num]=u;
    }
    int main()
    {
        sum=inf;
        scanf("%d",&n);
        memset(head,-1,sizeof(head));
        for(int i=1; i<n; i++)
        {
            scanf("%d%d",&x,&y);
            add(x,y);
        }
        dfs(1,0);
        sort(ans+1,ans+num+1);
        for(int i=1; i<num; i++)
            printf("%d ",ans[i]);
        printf("%d\n",ans[num]);
        return 0;
    }
    

     

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值