隐藏
「bsoj5221」树上的字符串 - 后缀平衡树 / 带撤销后缀自动机 | Bill Yang's Blog

路终会有尽头,但视野总能看到更远的地方。

0%

「bsoj5221」树上的字符串 - 后缀平衡树 / 带撤销后缀自动机

题目大意

    给定一棵有$n$个节点的树,根结点为$1$,每个节点有一个字母,然后要求分别输出每个节点到根节点这条路径上的不重复的子串个数。


题目分析

很显然,我们只需要维护根到当前点的所有字母,并快速统计其不重复子串个数。

后缀平衡树裸题。(写不来,等填坑)

当然我们可以使用后缀自动机水过去,但是后缀自动机不能撤销,怎么统计其他的链呢?暴力记录下每个点修改前的值,用栈存起来,最后暴力弹栈还原值。

时间复杂度可以算作前缀树的高度,故复杂度是$O(n\sqrt n)$的。
在随机数据下表现优良。


代码

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;
}
姥爷们赏瓶冰阔落吧~