zoukankan      html  css  js  c++  java
  • PKU 1655 Balancing Act(树+树的重心)

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #define maxn 20005
    using namespace std;
    struct Edge
    {
        int to;
        int next;
    }e[2*maxn];
    int t,n,x,y,tot;
    int head[maxn],num[maxn],balance[maxn];
    
    void Init()
    {
        tot=0;
        memset(head,-1,sizeof(head));
    } 
    void Addedge(int u,int v)
    {
        e[tot].to=v;
        e[tot].next=head[u];
        head[u]=tot++;
    }
    void dfs(int u,int pre)
    {
        balance[u]=0,num[u]=1;
        for(int i=head[u];i!=-1;i=e[i].next){
            int v=e[i].to;
            if(v==pre)
                continue ;
            dfs(v,u);
            balance[u]=max(balance[u],num[v]);
            num[u]+=num[v];
        }
        balance[u]=max(balance[u],n-num[u]);
    }
    int main()
    {
        scanf("%d",&t);
        while(t--){
            scanf("%d",&n);
            Init();
            for(int i=1;i<n;i++){
                scanf("%d%d",&x,&y);
                Addedge(x,y);
                Addedge(y,x);
            }
            dfs(1,-1);
            int pos=1,ans=balance[1];
            for(int i=2;i<=n;i++){
                if(balance[i]<ans){
                    pos=i;
                    ans=balance[i];
                }
            }
            printf("%d %d
    ",pos,ans);
        }
    }
  • 相关阅读:
    poj 2942 Knights of the Round Table 双连通分量
    zoj 2588 Burning Bridges 桥
    desin pattern
    android
    ubuntu
    centos
    android布局
    gradle
    好站
    tomcat datasource
  • 原文地址:https://www.cnblogs.com/freinds/p/6410584.html
Copyright © 2011-2022 走看看