POJ - 1655 Balancing Act (樹的重心)

Balancing Act

 

Consider a tree T with N (1 <= N <= 20,000) nodes numbered 1...N. Deleting any node from the tree yields a forest: a collection of one or more trees. Define the balance of a node to be the size of the largest tree in the forest T created by deleting that node from T.
For example, consider the tree:


Deleting node 4 yields two trees whose member nodes are {5} and {1,2,3,6,7}. The larger of these two trees has five nodes, thus the balance of node 4 is five. Deleting node 1 yields a forest of three trees of equal size: {2,6}, {3,7}, and {4,5}. Each of these trees has two nodes, so the balance of node 1 is two.

For each input tree, calculate the node that has the minimum balance. If multiple nodes have equal balance, output the one with the lowest number.

Input

The first line of input contains a single integer t (1 <= t <= 20), the number of test cases. The first line of each test case contains an integer N (1 <= N <= 20,000), the number of congruence. The next N-1 lines each contains two space-separated node numbers that are the endpoints of an edge in the tree. No edge will be listed twice, and all edges will be listed.

Output

For each test case, print a line containing two integers, the number of the node with minimum balance and the balance of that node.

Sample Input

1
7
2 6
1 2
1 4
4 5
3 7
3 1

Sample Output

1 2

題目鏈接:http://poj.org/problem?id=1655

題目大意:給一棵樹,求這棵樹的重心,和刪除重心後最大子樹的節點數

代碼:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N=2e4+10;
const int inf=1e9;
int tot,first[N],sum,root;
int siz[N],f[N]; 
struct node
{
    int v,nex;
}e[N<<1];
void add(int u,int v)
{
    e[tot].v=v;
    e[tot].nex=first[u];
    first[u]=tot++;
}
void getroot(int u,int fa) //求重心
{
    siz[u]=1,f[u]=0; //siz[u]記錄以u爲根的樹的節點個數,f[u]記錄以u爲根的最大子樹大小
    for(int i=first[u];~i;i=e[i].nex)
    {
        int v=e[i].v;
        if(v==fa) continue;
        getroot(v,u);
        siz[u]+=siz[v]; //加上子樹的節點數
        f[u]=max(f[u],siz[v]); //更新最大子樹大小
    }
    f[u]=max(f[u],sum-siz[u]); //以u爲根的話則之前的父節點也是子樹
    if(f[u]<f[root]) root=u;
}
void init()
{
    tot=0;
    memset(first,-1,sizeof(first));
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        init();
        int n;
        scanf("%d",&n);
        int u,v;
        for(int i=1;i<n;i++)
        {
            scanf("%d%d",&u,&v);
            add(u,v);
            add(v,u);
        }
        sum=n,root=0;
        f[0]=inf;
        getroot(1,0);
        printf("%d %d\n",root,f[root]);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章