|
Language:
Balancing Act
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 Source |
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define eps 1e-8
typedef __int64 ll;
using namespace std;
#define N 20005
int num[N],dp[N];
int head[N],k;
int n;
struct stud{
int to,next;
}e[N*2];
inline void add(int u,int v)
{
e[k].to=v;
e[k].next=head[u];
head[u]=k++;
}
void dfs(int x,int pre)
{
dp[x]=0;
num[x]=1;
int i;
for(i=head[x];i!=-1;i=e[i].next)
{
int to=e[i].to;
if(to==pre) continue;
dfs(to,x);
dp[x]=max(dp[x],num[to]);
num[x]+=num[to];
}
dp[x]=max(dp[x],n-num[x]); //例如树是 1 2 3 4 5,没有这一步 dp[5]就是0
}
int main()
{
int i,j,t;
scanf("%d",&t);
while(t--)
{
k=0;
memset(head,-1,sizeof(head));
scanf("%d",&n);
int u,v;
for(i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
add(u,v);
add(v,u);
}
dfs(1,-1);
int ans1=1,ans2=dp[1];
for(i=2;i<=n;i++)
if(dp[i]<ans2)
{
ans1=i;
ans2=dp[i];
}
printf("%d %d\n",ans1,ans2);
}
return 0;
}
本文探讨了一种算法问题,即在给定的树结构中找到删除后能形成最平衡森林的节点。通过深度优先搜索策略,计算每个节点被删除后形成的最大子树大小,进而找出具有最小平衡度的节点。
2056

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



