POJ - 1655 Balancing Act (树的重心)

Posted djh0709

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ - 1655 Balancing Act (树的重心)相关的知识,希望对你有一定的参考价值。

题目链接:https://vjudge.net/problem/POJ-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. 

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[i]是以节点i为根的树的节点总数,则去掉节点i后的树的节点总数为(n-dp[i]),从小到大枚举节点i,最后取max(dp[i],n-dp[i])即可。

AC代码:

#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=20000+10;
vector<int>p[maxn];
int dp[maxn],n,min_node,max_sum;
void DFS(int u,int fa){
	int sum=0;
	dp[u]=1;
	for(int i=0;i<p[u].size();i++){
		int v=p[u][i];
		if(v!=fa){
			DFS(v,u);
			dp[u]+=dp[v];
			sum=max(sum,dp[v]);
		}
	}
	sum=max(sum,n-dp[u]);
	if(sum<max_sum)
	{
		max_sum=sum;
		min_node=u;
	}
}
int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		int u,v;
		scanf("%d",&n);
		for(int i=1;i<=n;i++) p[i].clear();
		for(int i=1;i<n;i++)
		{
			scanf("%d%d",&u,&v);
			p[u].push_back(v);
			p[v].push_back(u);
		}
		max_sum=maxn;
		DFS(1,0);
		printf("%d %d
",min_node,max_sum);		
	}
}

  

 








以上是关于POJ - 1655 Balancing Act (树的重心)的主要内容,如果未能解决你的问题,请参考以下文章

POJ - 1655 Balancing Act (树的重心)

poj1655Balancing Act

Balancing Act(poj1655)

poj 1655 Balancing Act

POJ 1655Balancing Act

poj1655 Balancing Act