# POJ - 1655 Balancing Act（树的重心）

xiaoxiao2021-03-01  5

Time limit：1000 ms；Memory limit：65536 kB

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找到重心，并求出其最大连通块的结点数。

AC代码如下（157ms）：

/* * dp[i]表示以i为根的子树的结点个数 * dp[i] = Σdp[j] + 1; j是i的son * 结点i的最大连通块结点个数为max(dp[i],N-dp[i]) */ #include <vector> #include <algorithm> #include <stdio.h> using namespace std; #define fast ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long #define _for(i,a,b) for(int i = a;i < b;i++) #define rep(i,a,b) for(int i = a;i <= b;i++) const int maxn = 20010; int kase, N, ans[maxn]; vector<int>G[maxn];//邻接表 int dp[maxn]; bool flag[maxn];//记忆化处理。 void dfs(int r) { int sum, k; sum = k = 0; flag[r] = true;//标记经历过此点（此处一定要标记，否则死循环） int nson = G[r].size();//此点儿子的个数 _for(i, 0, nson) { int son = G[r][i]; if (!flag[son]) { dfs(son); sum += dp[son]; k = max(k, dp[son]); } else continue; } dp[r] = sum + 1;//以r为根的结点总个数 ans[r] = max(k, N - dp[r]);//以r为根的最大连通块的结点个数 } int main() { scanf("%d", &kase); while (kase--) { scanf("%d", &N); rep(i, 1, N)G[i].clear();//清空邻接表 memset(dp, 0, sizeof(dp)); memset(flag, false, sizeof(flag)); int x, y; _for(i, 0, N - 1) { scanf("%d%d", &x, &y); G[x].push_back(y); G[y].push_back(x); } int dot = 0; int cnt = maxn; dfs(1); rep(i, 1, N) { if (ans[i]<cnt) dot = i, cnt = ans[i]; } printf("%d %d\n", dot, cnt); } return 0; }