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
| #include <cstdio> #include <algorithm> using namespace std; const int N = 1e6 + 10, M = N << 1; int n, d[N], p[N], sz[N], son[N]; int mn, mx, cnt[N], ans[N]; int idx, hd[N], nxt[M], edg[M]; void dfs1(int x) { sz[x] = 1; son[x] = -1; for (int i = hd[x]; ~i; i = nxt[i]) if (!d[edg[i]]) { p[edg[i]] = x; d[edg[i]] = d[x] + 1; dfs1(edg[i]); sz[x] += sz[edg[i]]; if (son[x] == -1 || sz[edg[i]] > sz[son[x]]) son[x] = edg[i]; } } void update(int x, int op, int avoid) { cnt[d[x]] += op; if (cnt[d[x]] > mx) { mn = d[x]; mx = cnt[d[x]]; } else if (cnt[d[x]] == mx) mn = min(mn, d[x]); for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != p[x] && edg[i] != avoid) update(edg[i], op, avoid); } void dfs2(int x, int op) { for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != son[x] && edg[i] != p[x]) dfs2(edg[i], 0); if (~son[x]) dfs2(son[x], 1); update(x, 1, son[x]); ans[x] = mn - d[x]; if (!op) { update(x, -1, 0); mx = mn = 0; } } void add(int a, int b) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) hd[i] = -1; for (int i = 1, u, v; i < n; i++) { scanf("%d%d", &u, &v); add(u, v); add(v, u); } d[1] = 1; dfs1(1); dfs2(1, 0); for (int i = 1; i <= n; i++) printf("%d\n", ans[i]); return 0; }
|