POJ 1655 Balancing Act (树的重心)

点击打开链接

题意:给出一棵树,求树的重心的编号,并且输出最大子树的节点数目。如果有最大节点数目相同的情况,选取重心编号较小的输出。

树的重心:找到一个点,其所有的子树中最大的子树节点数最少,那么这个点就是这棵树的重心,删去重心后,生成的多棵树尽可能平衡。

比如样例,删除节点1,那么就会生成三棵子树,每个子树的节点数目都是2,这就是最平衡的情况了。如果多增加一条6 - 8的边,那么依然是选择删除节点1,生成三棵子树3 2 2也是最平衡的情况了。

求树的重心就是一遍dfs即可。

代码如下:

#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<utility>
#include<stack>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<set>
#include<map>
using namespace std;
const int maxn = 2e4 + 5;
int head[maxn], to[maxn << 1], nx[maxn << 1], tot;
bool vst[maxn];
int Min = 0x3f3f3f3f, key;
int cnt[maxn], n; 

void add_edge(int u, int v) {
	to[tot] = v, nx[tot] = head[u], head[u] = tot++;
	swap(u, v);
	to[tot] = v, nx[tot] = head[u], head[u] = tot++;
}

int dfs(int u, int par) {
	cnt[u] = 1;
	int Max = 0;
	for(int i = head[u]; ~i; i = nx[i]) {
		int v = to[i];
		if(v != par) {
			cnt[u] += dfs(v, u);
			Max = max(Max, cnt[v]);
		}
	}
	if(Max < n - cnt[u])
		Max = n - cnt[u];
	if(Max < Min) {
		Min = Max;
		key = u;
	} else if(Max == Min && key > u) {
		key = u;
	}
	return cnt[u];
}

int main() {
#ifndef ONLINE_JUDGE
//	freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
#endif
	int T;
	scanf("%d", &T);
	while(T--) {
		memset(head, -1, sizeof(head));
		tot = 0;
		Min = 0x3f3f3f3f;
		scanf("%d", &n);
		for(int i = 1, u, v; i < n; i++) {
			scanf("%d%d", &u, &v);
			add_edge(u, v);
		}
		dfs(1, 1);
		printf("%d %d\n", key, Min);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值