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
思路:
统计每个点的子树有多少个节点,同时记录子节点的子树中,有节点数量最多的子树,dp即可
dp[i]表示以节点i为根的子树有多少节点,f[i]表示以i为根的子树中,最多的节点分支数
代码:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<map>
#include<string>
#include<cstring>
#include<vector>
#include<algorithm>
#include<set>
#include<sstream>
#include<cstdio>
#include<unordered_map>
#include<unordered_set>
#include<cmath>
#include<climits>
using namespace std;
const int maxn=2e6+9;
int head[maxn];
int num;
int n,m;
int dp[maxn];
int f[maxn];
struct Edge
{
int u,v,w,next;
}edge[maxn];
void addEdge(int u,int v,int w)
{
edge[num].u=u;
edge[num].v=v;
edge[num].w=w;
edge[num].next=head[u];
head[u]=num++;
}
void init()
{
memset(head,-1,sizeof(head));
memset(dp,0,sizeof(dp));
memset(f,0,sizeof(f));
num=0;
}
void dfs(int u,int pre)
{
dp[u]=1;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(v==pre) continue;
dfs(v,u);
dp[u]+=dp[v];
f[u]=max(f[u],dp[v]);
}
}
int main(int argc, char const *argv[])
{
int T;
cin>>T;
while(T--)
{
init();
scanf("%d",&n);
for(int i=1;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
addEdge(x,y,0);
addEdge(y,x,0);
}
dfs(1,-1);
int ans=1e9+9;
int k=0;
for(int i=1;i<=n;i++)
{
int tmp;
tmp=max(n-dp[i],f[i]);
if(ans>tmp)
{
k=i;
ans=tmp;
}
}
printf("%d %d\n",k,ans);
}
return 0;
}