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
首先我们先介绍一下数重心定义
树的重心
性质1 重心到所有节点的距离和最小(边权为1)
性质2 两棵树合并,新的重心在两棵树重心的路径上
性质3 一棵树添加或删除一个节点,重心最多移动一条边的位置
性质4 重心的最大的子树的节点数最小
通俗说 就是去掉树中任意一点 找它的最大联通块 然后找出所有点中连通块最大值最小
见代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include<iostream>
using namespace std;
const int maxn = 1e5 + 5;
const int inf = 0x3f3f3f3f;
int t, n;
int y, h;
int head[maxn];
int tot;
int s[maxn], dp[maxn];
int minn;
struct node{
int e;
int next;
node(){}
node(int a, int b):e(a), next(b) {}
}edge[maxn];
void init(){
memset(head, -1, sizeof(head));
memset(s, 0, sizeof(s));
memset(dp, 0, sizeof(dp));
minn = inf;
tot = 0;
}
void edgeadd(int u, int v){
edge[tot] = node(v, head[u]);
head[u] = tot++;
edge[tot] = node(u, head[v]);
head[v] = tot++;
}
void dfs(int u, int p){
s[u] = 1;//s数组保存该节点的子节点数量
for(int i = head[u]; i != -1;i = edge[i].next){
int v = edge[i].e;
if(p == v) continue;
dfs(v, u);//用子节点信息更新该节点的子节点总数
s[u] += s[v];
if(dp[u] < s[v])
dp[u] = s[v];//dp数组保存删去u节点后,所有子连通块的最大节点数
//找到最大的子连通块的节点数
}
//对上下连通块中节点数进行比较 取最大 因为为树 所以必联通
dp[u] = max(dp[u], n - s[u]);
minn = min(minn, dp[u]);
}
int main(){
cin >> t;
while(t--){
init();
cin >> n;
for(int i = 1; i < n; i++){
cin >> y >> h;
edgeadd(y, h);
}
dfs(1, -1);
for(int i = 1; i <= n; i++){
if(dp[i] == minn)
printf("%d %d\n",i, dp[i]);
}
}
return 0;
}