poj1655 Balancing Act

Posted shixinyi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj1655 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


树形dp,只需要用到每个子树的大小。
水~
//Serene
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=2e4+10;
int T,n,tot;

int aa;char cc;
int read() {
	aa=0;cc=getchar();
	while(cc<‘0‘||cc>‘9‘) cc=getchar();
	while(cc>=‘0‘&&cc<=‘9‘) aa=aa*10+cc-‘0‘,cc=getchar();
	return aa;
}

int fir[maxn],nxt[2*maxn],to[2*maxn],e=0;
void add(int x,int y) {
	to[++e]=y;nxt[e]=fir[x];fir[x]=e;
	to[++e]=x;nxt[e]=fir[y];fir[y]=e;
}

struct Node{
	int pos,fa,size,maxnum;
}node[maxn];

void dfs(int pos) {
	node[pos].pos=pos;
	node[pos].size=1;
	for(int y=fir[pos];y;y=nxt[y]) {
		if(to[y]==node[pos].fa) continue;
		node[to[y]].fa=pos;dfs(to[y]);
		node[pos].maxnum=max(node[pos].maxnum,node[to[y]].size);
		node[pos].size+=node[to[y]].size;
	}
}

bool cmp(const Node& a,const Node& b) {
	int x=max(a.maxnum,tot-a.size),y=max(b.maxnum,tot-b.size);
	return x!=y? x<y:a.pos<b.pos;
}

int main() {
	T=read();
	int x,y;
	while(T--) {
		memset(fir,0,sizeof(fir));e=0;
		memset(node,0,sizeof(node));
		n=read();
		for(int i=1;i<n;++i) {
			x=read();y=read();
			add(x,y);
		}
		dfs(1);tot=node[1].size;
		sort(node+1,node+n+1,cmp);
		x=max(node[1].maxnum,tot-node[1].size);
		printf("%d %d\n",node[1].pos,x);
	}
	return 0;
}

  










以上是关于poj1655 Balancing Act的主要内容,如果未能解决你的问题,请参考以下文章

POJ 1655 Balancing Act (树的重心)

poj1655 Balancing Act

[POJ1655]Balancing Act

POJ - 1655 Balancing Act (树的重心)

Balancing Act(poj1655)

poj 1655 Balancing Act