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;
}