AIM Tech Round 3 C. Centroids 树形DP

Description
给你一棵树,问你对于每一个点是否可以在树上删掉一条边,再增加一条边,使它成为树的重心。
tips:一个点成为重心的条件为它的每个子树大小不超过n/2。


Sample Input
3
1 2
2 3


Sample Output
1 1 1


考虑先找到一个重心。
维护一个子树总和小于等于n/2的大小的最大值,次大值。
然后你往下递归的时候不断更新,就相当于把这个最大值子树断掉看他能否成为重心。


#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
	int s = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s * f;
}

struct edge {
	int x, y, next;
} e[810000]; int len, last[410000];
int n, mx1[410000], mx2[410000], bs[410000];
int tot[410000], ans[410000];

void ins(int x, int y) {
	e[++len].x = x, e[len].y = y;
	e[len].next = last[x], last[x] = len;
}

void dfs(int x, int fa) {
	tot[x] = 1; mx1[x] = mx2[x] = bs[x] = 0;
	for(int k = last[x]; k; k = e[k].next) {
		int y = e[k].y;
		if(y != fa) {
			dfs(y, x);
			tot[x] += tot[y];
			if(tot[y] > n / 2) bs[x] = tot[y];
			else if(tot[y] > mx1[x]) mx2[x] = mx1[x], mx1[x] = tot[y];
			else if(tot[y] > mx2[x]) mx2[x] = tot[y];
		}
	} if(n - tot[x] > n / 2) bs[x] = n - tot[x];
	else if(n - tot[x] > mx1[x]) mx2[x] = mx1[x], mx1[x] = n - tot[x];
	else if(n - tot[x] > mx2[x]) mx2[x] = n - tot[x];
}

void dfs2(int x, int fa, int s) {
	if(!bs[x]) ans[x] = 1;
	else if(n - tot[x] - s <= n / 2) ans[x] = 1;
	for(int k = last[x]; k; k = e[k].next) {
		int y = e[k].y;
		if(y != fa) {
			if(mx1[x] != tot[y]) dfs2(y, x, _max(s, mx1[x]));
			else dfs2(y, x, _max(s, mx2[x]));
		}
	}
}

int main() {
	n = read();
	for(int i = 1; i < n; i++) {
		int x = read(), y = read();
		ins(x, y), ins(y, x);
	} dfs(1, 0);
	int rt;
	for(int i = 1; i <= n; i++) if(!bs[i]) {rt = i; break;}
	dfs(rt, 0);
	dfs2(rt, 0, 0);
	for(int i = 1; i <= n; i++) printf("%d ", ans[i]);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值