1. 程式人生 > >Godfather POJ

Godfather POJ

  • 的重心也叫的質心。找到一個點,其所有的子樹中最大的子樹節點數最少,那麼這個點就是這棵樹的重心,刪去重心後,生成的多棵樹儘可能平衡。
  • 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;
    }