, 听说可以长链剖分,但是不会啊!
因为我们要维护每个点子树为 dep 的个数,考虑线段树合并,将子树的dep信息合并到父亲
所以以dep为下标建立线段树,然后线段树维护区间最大值,也就是查dep出现次数最多的点
#include<bits/stdc++.h>
#define N 1000050
using namespace std;
int first[N], nxt[N<<1], to[N<<1], tot;
void add(int x, int y){
nxt[++tot] = first[x], first[x] = tot, to[tot] = y;
}
int n, dep[N], ans[N], res;
int rt[N], Max[N * 22], ls[N * 22], rs[N * 22], id[N * 22];
void Pushup(int x){
if(Max[ls[x]] >= Max[rs[x]]){ Max[x] = Max[ls[x]]; id[x] = id[ls[x]];}
else{ Max[x] = Max[rs[x]]; id[x] = id[rs[x]];}
}
void Insert(int &x, int l, int r, int p){
if(!x) x = ++res;
if(l == r) { Max[x]++; id[x] = l; return;}
int mid = (l+r) >> 1;
if(p <= mid) Insert(ls[x], l, mid, p);
else Insert(rs[x], mid+1, r, p); Pushup(x);
}
int Merge(int x, int y, int l, int r){
if(!x || !y) return x + y;
if(l == r){ Max[x] += Max[y]; id[x] = l; return x;}
int mid = (l+r) >> 1;
ls[x] = Merge(ls[x], ls[y], l, mid);
rs[x] = Merge(rs[x], rs[y], mid+1, r);
Pushup(x); return x;
}
void dfs(int u, int fa){
Insert(rt[u], 1, n, dep[u]);
for(int i=first[u];i;i=nxt[i]){
int t = to[i]; if(t == fa) continue;
dep[t] = dep[u] + 1; dfs(t, u);
rt[u] = Merge(rt[u], rt[t], 1, n);
} ans[u] = id[rt[u]] - dep[u];
}
int main(){
Max[0] = -1e9;
scanf("%d", &n);
for(int i=1; i<n; i++){
int x, y; scanf("%d%d", &x, &y);
add(x, y); add(y, x);
} dep[1] = 1; dfs(1, 0);
for(int i=1; i<=n; i++) printf("%d\n", ans[i]);
return 0;
}