Balancing Act
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 9048 | Accepted: 3747 |
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.
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,dfs搜一遍就可以了。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
int T,t,n,ans[2],num[20010];
vector <int> vc[20010];
void dfs(int f,int u)
{
int i,j,k,v,len=vc[u].size(),maxn=0;
for(i=0;i<len;i++)
{
v=vc[u][i];
if(f==v)
continue;
dfs(u,v);
num[u]+=num[v];
maxn=max(maxn,num[v]);
}
maxn=max(maxn,n-num[u]);
if(maxn<ans[1])
{
ans[0]=u;ans[1]=maxn;
}
else if(maxn==ans[1])
ans[0]=min(ans[0],u);
}
int main()
{
int i,j,k,u,v;
scanf("%d",&T);
for(t=1;t<=T;t++)
{
scanf("%d",&n);
for(i=1;i<=n;i++)
{
vc[i].clear();
num[i]=1;
}
for(i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
vc[u].push_back(v);
vc[v].push_back(u);
}
ans[1]=n;
dfs(0,1);
printf("%d %d\n",ans[0],ans[1]);
}
}

本博客探讨了在给定树结构中,通过删除某个节点后形成森林的节点数量来定义节点的平衡,并计算每个节点的平衡值。重点在于找出平衡值最小的节点,若多个节点平衡值相同,则选择编号最小的节点。通过树形DP方法解决此问题。

被折叠的 条评论
为什么被折叠?



