POJ 1655 Balancing Act(赠送POJ 3倍经验卡)

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6769   Accepted: 2718

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

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

Sample Output

1 2

思想就是树形dfs搜索,用一个数组num[i]记录结点i的(叶子节点个数+1),则该结点的Balance就是一下几种情况的最大值:
1.该节点的相邻子结点i的num[i];
2.该节点的非子结点的个数,该结点为i时也就是n-num[i];
Balance[i]=max(num[j](j为i的所有子节点),n-num[i]);
搜索即可。
记录时用变量Max记录每个节点的Balance值时要把Max定义在DFS()函数内,因为每个节点对应一个Max。

易错点:
1.ansNum,ansNode没有初始化。
2.建邻接表时Edge【】数组应该为所给边的2倍,因为是双向边。
3.Max变量应该定义在dfs()函数内
这道题AC了以后,会得给一张3倍经验卡,A一题,顶3题。
附3倍经验卡:
POJ 1655:http://poj.org/problem?id=1655
POJ 2378:http://poj.org/problem?id=2378
POJ 3107:http://poj.org/problem?id=3107


几乎一模一样,改了一小部分。
原文地址:https://www.cnblogs.com/liuyalunuli/p/2704437.html