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
| #include <bits/stdc++.h> #define fi first #define se second const int N = 5e5 + 100; int n, ct[N], dep[N], son[N], si[N]; int h[N], idx = 0, as[24], cnt[(1 << 22) + 100], ans[N], cp, cq; std::pair<int, int> p[N]; struct Edge{ int ne, ver, w; } e[N << 1]; void add(int x, int y, int z){ e[idx] = {h[x], y, z}, h[x] = idx++; } void dfs(int x, int fa, int c) { dep[x] = dep[fa] + 1, si[x] = 1, ct[x] = c; for (int i = h[x], y; ~i; i = e[i].ne) if (!dep[y = e[i].ver]) { dfs(y, x, c ^ (1 << e[i].w)); si[x] += si[y]; if (si[y] > si[son[x]]) son[x] = y; } } void walk(int x, int fa) { p[++cp] = {ct[x], dep[x]}; for (int i = h[x]; ~i; i = e[i].ne) if (e[i].ver != fa) walk(e[i].ver, x); } void calc(int x, int fa, int is) { for (int i = h[x], y; ~i; i = e[i].ne) if ((y = e[i].ver) != fa && y != son[x]) { calc(y, x, 0); ans[x] = std::max(ans[x], ans[y]); } if (son[x]) calc(son[x], x, 1), ans[x] = std::max(ans[x], ans[son[x]]); for (int *t = as; t != as + 23; ++t) if (cnt[ct[x] ^ *t]) ans[x] = std::max(ans[x], cnt[ct[x] ^ *t] - dep[x]); cnt[ct[x]] = std::max(cnt[ct[x]], dep[x]); for (int i = h[x], y; ~i; i = e[i].ne) if ((y = e[i].ver) != fa && y != son[x]) { cp = 0; walk(y, x); for (int j = 1; j <= cp; ++j) for (int *t = as; t != as + 23; ++t) if (cnt[p[j].fi ^ *t]) ans[x] = std::max(ans[x], cnt[p[j].fi ^ *t] + p[j].se - (dep[x] << 1)); for (int j = 1; j <= cp; ++j) cnt[p[j].fi] = std::max(cnt[p[j].fi], p[j].se); } if (!is) { cp = 0; walk(x, fa); for (int i = 1; i <= cp; ++i) cnt[p[i].fi] = 0; } } int main() { scanf("%d", &n); std::memset(h, -1, (n + 1) << 2); for (int i = 2, p; i <= n; ++i) { char c[2]; scanf("%d %s", &p, c); add(i, p, c[0] - 'a'), add(p, i, c[0] - 'a'); } as[0] = 0; for (int i = 0; i < 22; ++i) as[i + 1] = 1 << i; dfs(1, -1, 0), calc(1, -1, 1); for (int i = 1; i <= n; ++i) printf("%d ", ans[i]); return 0; }
|