POJ 1655 Balancing Act

来源:互联网 发布:清理上网痕迹软件 编辑:程序博客网 时间:2024/05/18 03:28

Description

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

172 61 21 44 53 73 1

Sample Output

1 2
题意:给你一个数n,表示有n-1条边,要你求出以某个点为根节点的树,使得它的子树的节点最多
思路:树形DP里的的树的重心问题,要实现也很简单:只要DFS一次d(i)=d[j]+1的和,d(j)表示节点i的子节点,弄出来后找出最大的就可以了!
AC代码:
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define inf 0xfffff#define N 20005int n;struct p    //maxx记录最大的,{    int maxx,sum;}d[N];struct node{    int u,v;}edge[N<<2];int head[N],tot;void addedge(int a,int b){    edge[tot].u=b,edge[tot].v=head[a],head[a]=tot++;}int dfs(int u,int pre){    d[u].sum=1;    d[u].maxx=0;    for(int i=head[u];~i;i=edge[i].v)    {        if(edge[i].u!=pre)        {            int t=dfs(edge[i].u,u);            d[u].sum+=t;            d[u].maxx=max(d[u].maxx,t);        }    }    return d[u].sum;}int main(){    int t;    scanf("%d",&t);    while(t--)    {        int i,j;        scanf("%d",&n);        tot=0;        memset(head,inf,sizeof(int)*(n+3));        for(i=0;i<n-1;i++)        {            int a,b;            scanf("%d %d",&a,&b);            addedge(a,b);            addedge(b,a);        }        dfs(1,0);        int ans=inf,gen;        for(i=1;i<=n;i++)        {            d[i].maxx=max(d[i].maxx,n-d[i].sum);            if(ans>d[i].maxx)            {                gen=i;                ans=d[i].maxx;            }        }        printf("%d %d\n",gen,ans);    }    return 0;}


0 0