您的位置:首页 > 其它

poj 1655 Balancing Act 树的重心

2015-03-26 00:02 399 查看
题目链接:http://poj.org/problem?id=1655

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.

题意描述:略。找出重心以及删除重心后两颗子树中结点数大的一颗。

算法分析:重在分析重心问题,一颗树的重心就是所有节点的子节点的数量最大的最小的节点。简而言之,重心就是要让这棵树在节点个数上达到左右子树相对平衡的这样一个节点。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<queue>
#include<vector>
#define inf 0x7fffffff
using namespace std;
const int maxn=20000+10;
const int M = 20000+10;

int n;
struct node
{
int v,next;
}edge[M*3];
int head[maxn],edgenum;

void add(int u,int v)
{
edge[edgenum].v=v ;edge[edgenum].next=head[u] ;head[u]=edgenum++ ;
edge[edgenum].v=u ;edge[edgenum].next=head[v] ;head[v]=edgenum++ ;
}

int an[maxn],bn[maxn];
int dfs(int u,int pre)
{
an[u]=bn[u]=1;
for (int i=head[u] ;i!=-1 ;i=edge[i].next)
{
int v=edge[i].v;
if (v != pre)
{
int k=dfs(v,u);
an[u] += k;
bn[u]=max(bn[u],k);
}
}
return an[u];
}

int main()
{
int t;
scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
memset(head,-1,sizeof(head));
edgenum=0;
int a,b;
for (int i=1 ;i<n ;i++)
{
scanf("%d%d",&a,&b);
add(a,b);
}
int k=dfs(1,1);
int ans=inf,num=n;
for (int i=1 ;i<=n ;i++)
{
bn[i]=max(bn[i],n-an[i]);
if (ans>bn[i] || (ans==bn[i] && n>i))
{
ans=bn[i];
num=i;
}
}
printf("%d %d\n",num,ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: