1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| #include <bits/stdc++.h> #define MAXN 1000006 using namespace std;
int n, cnt, maxnum, maxans, siz[MAXN], head[MAXN], dep[MAXN], ans[MAXN], num[MAXN], tag[MAXN];
struct Edge {int next, to;}edge[MAXN*2];
void addedge(int from, int to) { edge[++cnt].next=head[from]; edge[cnt].to=to; head[from]=cnt; }
void dfs1(int x, int fa) { siz[x]=1; for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa) continue; dep[to]=dep[x]+1; dfs1(to, x); siz[x]+=siz[to]; } }
void update(int x) { if(num[dep[x]]>maxnum) maxnum=num[dep[x]], maxans=dep[x]; if(num[dep[x]]==maxnum && dep[x]<maxans) maxans=dep[x]; }
void add(int x, int fa, int op) { num[dep[x]]+=op; update(x); for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa) continue; add(to, x, op); } }
void dfs2(int x, int fa, int keep) { int maxson=-1, maxsize=0; for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa) continue; if(siz[to]>maxsize) maxson=to, maxsize=siz[to]; }
for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa || to==maxson) continue; dfs2(to, x, 0); } if(maxson!=-1) dfs2(maxson, x, 1);
num[dep[x]]++; update(x); for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa || to==maxson) continue; add(to, x, 1); } ans[x]=maxans;
if(keep==0) { num[dep[x]]--; update(x); for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa) continue; add(to, x, -1); } maxnum=maxans=0; } }
int main() { scanf("%d", &n); for(int i=1; i<n; i++) { int x, y; scanf("%d%d", &x, &y); addedge(x, y); addedge(y, x); } dfs1(1, 0); dfs2(1, 0, 1); for(int i=1; i<=n; i++) printf("%d\n", ans[i]-dep[i]); }
|