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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| #include<iostream> #include<cstdio> #include<algorithm> #define ll long long using namespace std;
const ll N=5e5;
ll n,v,tmpans,lca,tot;
ll ver[N*2+5],nxt[N*2+5],wt[N*2+5],head[N+5];
ll ans[N+5],siz[N+5],dt[N+5],dep[(1ll<<23)+5],val[N+5],hs[N+5];
inline void dfs(ll p,ll fath) { siz[p]=1;dt[p]=dt[fath]+1; for(ll i=head[p];i;i=nxt[i]) { if(ver[i]==fath) continue; val[ver[i]]=val[p]^(1ll<<wt[i]); dfs(ver[i],p); if(siz[ver[i]]>siz[hs[p]]) hs[p]=ver[i]; siz[p]+=siz[ver[i]]; } }
inline void getans(ll p,ll fath) { for(ll j=0;j<22;j++) { if(dep[(1ll<<j)^val[p]]) tmpans=max(tmpans,dt[p]+dep[(1ll<<j)^val[p]]-2*dt[lca]); } if(dep[0^val[p]]) tmpans=max(tmpans,dt[p]+dep[0^val[p]]-2*dt[lca]); for(ll i=head[p];i;i=nxt[i]) { if(ver[i]==fath) continue; getans(ver[i],p); } }
inline void modify(ll p,ll fath) { dep[val[p]]=max(dep[val[p]],dt[p]); for(ll i=head[p];i;i=nxt[i]) { if(ver[i]==fath) continue; modify(ver[i],p); } }
inline void clear(ll p,ll fath) { dep[val[p]]=0; for(ll i=head[p];i;i=nxt[i]) { if(ver[i]==fath) continue; clear(ver[i],p); } }
inline void dfs_(ll p,ll fath,bool kp) { for(ll i=head[p];i;i=nxt[i]) { if(ver[i]==fath||ver[i]==hs[p]) continue; dfs_(ver[i],p,0);ans[p]=max(ans[p],ans[ver[i]]); } if(hs[p]) {dfs_(hs[p],p,1);ans[p]=max(ans[p],ans[hs[p]]);} tmpans=ans[p];lca=p; for(ll i=head[p];i;i=nxt[i]) { if(ver[i]==hs[p]||ver[i]==fath) continue; getans(ver[i],p);modify(ver[i],p); } for(ll j=0;j<22;j++) { if(dep[(1ll<<j)^val[p]]) tmpans=max(tmpans,dt[p]+dep[(1ll<<j)^val[p]]-2*dt[lca]); } if(dep[0^val[p]]) tmpans=max(tmpans,dt[p]+dep[0^val[p]]-2*dt[lca]); dep[val[p]]=max(dep[val[p]],dt[p]); ans[p]=max(ans[p],tmpans); if(!kp) { for(ll i=head[p];i;i=nxt[i]) { if(ver[i]==fath) continue; clear(ver[i],p); } dep[val[p]]=0; } }
inline void addedge(ll u,ll v,ll w) { ver[++tot]=v;wt[tot]=w;nxt[tot]=head[u];head[u]=tot; }
inline ll read() { ll ret=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9') {if(ch=='-') f=-f;ch=getchar();} while(ch>='0'&&ch<='9') {ret=(ret<<3)+(ret<<1)+ch-'0';ch=getchar();} return ret*f; }
inline void write(ll x) { static char buf[22];static ll len=-1; if(x>=0) { do{buf[++len]=x%10+48;x/=10;}while(x); } else { putchar('-'); do{buf[++len]=-(x%10)+48;x/=10;}while(x); } while(len>=0) putchar(buf[len--]); }
inline void writeln(ll x) { write(x);putchar('\n'); }
int main() { n=read(); for(ll i=2;i<=n;i++) { char ch[3]; v=read();scanf("%s",ch); addedge(v,i,ch[0]-'a');addedge(i,v,ch[0]-'a'); }
dfs(1,0);dfs_(1,0,1); for(ll i=1;i<=n;i++) { write(ans[i]);putchar(' '); } return 0; }
|