AIM Tech Round 3 C. Centroids樹形DP
阿新 • • 發佈:2018-12-13
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;
}