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
| #include<algorithm> #include<iostream> #include<iomanip> #include<cstring> #include<cstdlib> #include<vector> #include<cstdio> #include<cmath> #include<queue> #include <stack> using namespace std;
inline const int Get_Int() { int num=0,bj=1; char x=getchar(); while(x<'0'||x>'9') { if(x=='-')bj=-1; x=getchar(); } while(x>='0'&&x<='9') { num=num*10+x-'0'; x=getchar(); } return num*bj; }
const int maxn=200005,maxc=26;
struct St { int &x,v; };
stack<St>S;
struct SuffixAutomaton { int cnt,root,last; int next[maxn*2],Max[maxn*2]; int child[maxn*2][maxc]; SuffixAutomaton() { cnt=0; root=last=newnode(0); } int newnode(int val) { cnt++; next[cnt]=0; Max[cnt]=val; memset(child[cnt],0,sizeof(child[cnt])); return cnt; } void backup(int& now) { S.push((St) {now,now}); } int insert(int data) { int p=last,u=newnode(Max[last]+1); backup(last); last=u; for(; p&&!child[p][data]; p=next[p])backup(child[p][data]),child[p][data]=u; if(!p)backup(next[u]),next[u]=root; else { int old=child[p][data]; if(Max[old]==Max[p]+1)backup(next[u]),next[u]=old; else { int New=newnode(Max[p]+1); for(int i=0; i<26; i++)backup(child[New][i]),child[New][i]=child[old][i]; backup(next[New]); next[New]=next[old]; backup(next[u]),backup(next[old]); next[u]=next[old]=New; for(; child[p][data]==old; p=next[p])backup(child[p][data]),child[p][data]=New; } } return Max[u]-Max[next[u]]; } void rollback(int last) { while(S.size()>last) { St &top=S.top(); top.x=top.v; S.pop(); } } } sam;
int n,Ans[maxn]; char ch[maxn]; vector<int>edges[maxn];
void AddEdge(int x,int y) { edges[x].push_back(y); }
void Dfs(int Now,int father) { int top=S.size(); Ans[Now]=Ans[father]+sam.insert(ch[Now]-'a'); for(int Next:edges[Now]) { if(Next==father)continue; Dfs(Next,Now); } sam.rollback(top); }
int main() { n=Get_Int(); for(int i=1; i<n; i++) { int x=Get_Int(),y=Get_Int(); AddEdge(x,y); AddEdge(y,x); } scanf("%s",ch+1); Dfs(1,0); for(int i=1; i<=n; i++)printf("%d\n",Ans[i]); return 0; }
|