0%

浅谈AC自动机

浅谈AC自动机

$\color{lightblue}Status: OK$

前置内容

AC自动机是用 Trie 树构建的,所以在学AC自动机之前,你需要先学会 Trie。

用来做什么

在一个串内匹配多个模式串,并对匹配结果进行若干操作。

利用 fail 数组解决多种问题。

在 AC自动机上 DP。

如何实现

先上模板题链接:P3808 AC自动机(简单版)。

插入

把所有的模式串插入 Trie 中,时间复杂度为 $O(\sum_{i=1}^n |s_i|)$。

构建 fail 边

现在,我们要对 Trie 上的每个节点 $i$,计算出从根节点到它形成的这个字符串,能和这个串的一个后缀匹配的所有模式串的前缀中的最长前缀,用 $fail[i]$ 存储这个前缀处在的节点。

假设现在有一个节点 $x$,它的父亲是 $p$,且满足 $tr[p][c] = x$,我们已经求出了 $p$ 节点的 fail。

显然,$fail[x] = tr[fail[p]][c]$,因为 $fail[p]$ 存储的是能和 $p$ 匹配的最长前缀,所以同时加上一个 $c$,必然还是前缀。

至于为啥最长,如果有比它更长的,那么同时减去一个 $c$,它必然是 $p$ 的更长的前缀,和 fail 的定义冲突,所以最长。

这时候,你可能会问:如果 $fail[p]$ 所在的节点没有 $c$ 这个儿子,怎么办呢?

我们强行让它有这个儿子,即 $tr[p][c] = tr[fail[p]][c]$。

仔细想想,这就相当于一个路径压缩的过程,没有就指向上一次有的,每次都指,不就是一个并查集吗?所以这样指是合法的。

至此,fail 构建的方法已经出来了,正确性也有了保证。

再想一想我们构建一个节点 fail 的前提:它的父亲的 fail 已经构建出来。

这提示我们什么?要用 BFS 完成构建。

先插入根节点所有存在的儿子(不直接插入根节点是因为,根据上面的规则,它的儿子会把 fail 都设成自己),之后每次取出一个儿子,把所有子节点的 fail 更新或创建子节点,原来已经有的子节点入队,更新它的儿子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (int i=0;i<26;i++) if (tr[0][i]) q.push(tr[0][i]);
int now;
while (!q.empty()){
now = q.front();
q.pop();
int fai = fail[now];
for (int i=0;i<26;i++){
if (!tr[now][i]) tr[now][i] = tr[fai][i];
else{
fail[tr[now][i]] = tr[fai][i];
q.push(tr[now][i]);
}
}
}

完成这项操作的时间复杂度最大为 $O(26\sum_{i=1}^n|s_i|)$。

Bonus:fail 边构成的图为 fail 树,fail 边和 Trie 树组成的图叫 fail图。请你证明一下 fail 边构成的一定是个树。

查询

以这道题中的查询为例,我们需要查询有多少个模式串在匹配串中出现。

把匹配串放到 AC自动机上面跑(其实就是 Trie+fail 边组成的图),可以对每个前缀跑出来一个匹配的最长后缀,之后不断走 fail 边,即可遍历这个后缀的所有后缀,最后累加一下是串的结尾的后缀即可。注意已经访问过的后缀不用再访问,因为后面走的所有点都走过了,这样可以使每个点都只被访问一次,降低复杂度。

查询的过程和 KMP 非常类似,只不过其中的模式串由单串变为了多串,查找的也是所有模式串中的 LCP。

Code

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
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
int n,tr[N][26],tot,fail[N],ans,exi[N];
char s[N];
queue<int> q;
void insert(char *s){
int len = strlen(s+1),now = 0;
for (int i=1;i<=len;i++){
int c = s[i]-'a';
if (!tr[now][c]) tr[now][c] = ++tot;
now = tr[now][c];
}
exi[now]++;
}
void build(){
for (int i=0;i<26;i++) if (tr[0][i]) q.push(tr[0][i]);
int now;
while (!q.empty()){
now = q.front();
q.pop();
int fai = fail[now];
for (int i=0;i<26;i++){
if (!tr[now][i]) tr[now][i] = tr[fai][i];
else{
fail[tr[now][i]] = tr[fai][i];
q.push(tr[now][i]);
}
}
}
}
void query(char *s){
int len = strlen(s+1);
int now = 0;
for (int i=1;i<=len;i++){
int c = s[i]-'a';
now = tr[now][c];
int tmp = now;
while (tmp && exi[tmp]!=-1){
ans+=exi[tmp];
exi[tmp] = -1;
tmp = fail[tmp];
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for (int i=1;i<=n;i++){
cin>>(s+1);
insert(s);
}
build();
cin>>(s+1);
query(s);
cout<<ans<<endl;
return 0;
}

总结一下,AC自动机可以完成多模式串匹配,fail 边指向的是和这个串的后缀匹配的模式串的最长前缀,构建一个AC自动机的时间复杂度和空间复杂度均为 $O(26\sum|s_i|)$。

练习

P3796 AC自动机(加强版)

拓展

不妨想想,AC自动机能拥有这样好的性能的原因是什么?不难发现,一切的奥秘都在 fail 边之中。正是因为添加了 fail 边,才能 $O(1)$ 找到最长公共后缀,这启发我们:还可以拿 fail 边干点啥别的事吗?

拓扑建图优化计数

P5357 AC 自动机(二次加强版)

先说一个朴素的做法。

把AC自动机建出来,再把 $s$ 放上去匹配,每次匹配时,不断跳 fail 边,再把遇到的结束位置的计数器加 $1$。

这样的时间复杂度是多少呢?每次跳 fail 边最少使长度减 $1$,最多要跳 $\max(|t_i|)$ 次,总时间复杂度为 $O(|s||t|)$。

但是,这样会带来大量重复的计算。因为 fail 边构成的一定是树,所以我们可以利用 DAG 的性质。

比如,我们从 $a$ 跳到 $b$,再跳到 $c$,把 $b,c$ 的计数器都加 $1$,下一次我们又来到了 $b$,又要跳到 $c$。发现了什么,这个跳的过程是可以合并的。我们第一次从 $a\rightarrow b$ 之后,不继续跳了,只是跟 $b$ 说你多跳一次,也就是把 $b$ 的计数器加 $1$。

既然这样,每个节点跳 fail 之前就有一个限制:所有要跳到它的节点都已经被访问过了。

学术一点说,就是它的入度要为 $0$,这就可以用拓扑排序解决了。

Code

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
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+10,M = 2e6+10;
int n,tr[N][26],fail[N],tot,mp[N],indeg[N],ans[N];
char s[M];
queue<int> q;
void insert(char *s,int id){
int len = strlen(s+1),now = 0;
for (int i=1;i<=len;i++){
int c = s[i]-'a';
if (!tr[now][c]) tr[now][c] = ++tot;
now = tr[now][c];
}
mp[id] = now;
}
void build(){
for (int i=0;i<26;i++) if (tr[0][i]) q.push(tr[0][i]);
int now;
while (!q.empty()){
now = q.front(),q.pop();
int fa = fail[now];
for (int i=0;i<26;i++){
if (!tr[now][i]) tr[now][i] = tr[fa][i];
else{
fail[tr[now][i]] = tr[fa][i];
indeg[tr[fa][i]]++;
q.push(tr[now][i]);
}
}
}
}
void query(char *s){
int len = strlen(s+1),now = 0;
for (int i=1;i<=len;i++){
int c = s[i]-'a';
now = tr[now][c];
ans[now]++;
}
}
void topo(){
for (int i=1;i<=tot;i++){
if (!indeg[i]) q.push(i);
}
int now;
while (!q.empty()){
now = q.front(),q.pop();
ans[fail[now]]+=ans[now];
indeg[fail[now]]--;
if (!indeg[fail[now]]) q.push(fail[now]);
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for (int i=1;i<=n;i++){
cin>>(s+1);
insert(s,i);
}
build();
cin>>(s+1);
query(s);
topo();
for (int i=1;i<=n;i++) cout<<ans[mp[i]]<<"\n";
return 0;
}

练习

P3041 [USACO12JAN]Video Game G

(这题不用拓扑建图也能水过去,但是万一被加强了呢?)

P3065 [USACO12DEC]First! G

(这题其实也是诈骗,因为虽然要拓扑排序,但是跟这里的拓扑建图没有任何关系,甚至不用AC自动机)

套上 DP

P4052 [JSOI2007]文本生成器

先用一个容斥,把问题转化为求不可读文本的数量。

假设我们匹配一个串,它什么时候不可读?

显然,把它放在 AC 自动机上匹配,一直匹配不到末尾节点,就不可读。

看到计数,自然想到 DP,而这个 DP 状态,根据某些大佬的说法,一般都是设 $f[i][j]$ 表示串的长度为 $i$,匹配到 AC自动机上的 $j$ 节点,转移也是非常套路的枚举 $i,j$ 和这次加入的字符。时间复杂度为 $O(26|s||\sum t_i|)$。

放个转移方程:

$f[i+1][tr[j][p]]+=f[i][j]$

条件是 $tr[j][p]$ 不为终止节点,且 $j$ 也不为终止节点(不要也行,因为前面的条件就限制了 $f[i][j]$ 必定为 $0$)。

初始化时把 $f[0][0]$ 初始化为 $1$。

Code

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
#include<bits/stdc++.h>
using namespace std;
const int N = 1e4+10,M = 1e2+10,mod = 1e4+7;
int n,m,tr[N][26],ok[N],fail[N],tot,f[M][N];
char s[N];
queue<int> q;
void insert(char *s){
int len = strlen(s+1),now = 0;
for (int i=1;i<=len;i++){
int c = s[i]-'A';
if (!tr[now][c]) tr[now][c] = ++tot;
now = tr[now][c];
}
ok[now] = 1;
}
void build(){
for (int i=0;i<26;i++) if (tr[0][i]) q.push(tr[0][i]);
int now;
while (!q.empty()){
now = q.front(),q.pop();
int fa = fail[now];
for (int i=0;i<26;i++){
if (!tr[now][i]) tr[now][i] = tr[fa][i];
else{
fail[tr[now][i]] = tr[fa][i];
ok[tr[now][i]]|=ok[tr[fa][i]];
q.push(tr[now][i]);
}
}
}
}
int ksm(int x,int y){
int ret = 1,bas = x;
while (y){
if (y&1) ret = ret*bas%mod;
bas = bas*bas%mod;
y>>=1;
}
return ret;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
for (int i=1;i<=n;i++){
cin>>(s+1);
insert(s);
}
build();
int ans = ksm(26,m);
f[1][0] = 1;
for (int i=1;i<=m;i++){
for (int j=0;j<=tot;j++){
for (int p=0;p<26;p++){
if (!ok[tr[j][p]]) f[i+1][tr[j][p]] = (f[i+1][tr[j][p]]+f[i][j])%mod;
}
}
}
for (int i=0;i<=tot;i++) ans = (ans-f[m+1][i])%mod;
ans = (ans+mod)%mod;
cout<<ans<<endl;
return 0;
}

在 AC自动机上 DP 的题还有很多,最重要的就是状态转移方程,所以要好好理解 AC自动机的原理和各个细节的含义。

练习

P3311 [SDOI2014] 数数

P2292 [HNOI2004] L 语言

在 fail 树上 dfs

P2444 POI2000 病毒

所谓不包含病毒串,就是这个串在 Trie 上匹配时,不会走到病毒串的末尾。

所谓无限长的串,就是 dfs 整个 Trie 时会形成环。

一个节点会走到病毒串的末尾,条件是这个串一直跳 fail,会跳到病毒串末尾,于是我们只要知道它的 fail 是否跳到病毒串末尾,就可以知道它是否会跳到了。

dfs 时对每个走过的点打上标记,如果走到了经过的点,就说明找到环了。

代码就不放了,相信大家的能力!实际上是我之前写了一个很慢的 dp,懒的再写一个了

在 fail 树上求 lca

P4600 HEOI2012 旅行问题

神仙题。

为啥这题神仙,因为你如果不想 AC(自动机),不想 fail(树),那就无法可想了。不信你用其他的方法搞1h,能搞出来算我输;您再想1h,不看题解能想到lca上,那您就是神仙了

废话不多说,我们直接分析如何做。(也别管是怎么想到的了)

显然,AC自动机上的每一个点的 fail 边指向的都是最长后缀,且这个后缀必然是一个字符串的前缀(根据 Trie 的性质)。

之后,我们求两个点在 fail 树上的 lca,思考其意义。

显然,从根节点到 lca 的链是两个点对应的串的后缀(毕竟能跳 fail 到那里去),且是最长公共后缀(你想想啥是 lca),而且还是其中一个字符串的子串(它在 Trie 上)。

这不就是我们要求的东西吗?

温馨提示:此题卡空间,您如果用倍增求 lca 可能会挂掉 $2$ 个点,在此放上常数巨大无比的转 dfs 序后用线段树求 lca 的代码。不会树剖锕

Code

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
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+5,mod = 1e9+7;
int n,m,val[N],head[N],tot,cnt,col,ori[N],beg[N],en[N],dfn[N*2];
char s[N];
queue<int> q;
vector<int> pre[N];
struct e{
int next,to;
} edge[N];
void add(int x,int y){
edge[++tot].to = y;
edge[tot].next = head[x];
head[x] = tot;
}
struct SegT{
int Min[N*8];
void pushup(int node){
Min[node] = min(Min[node<<1],Min[node<<1|1]);
}
void build(int node,int l,int r){
if (l == r){
Min[node] = dfn[l];
return;
}
int mid = (l+r)>>1,lc = node<<1,rc = node<<1|1;
build(lc,l,mid);
build(rc,mid+1,r);
pushup(node);
}
int query(int node,int beg,int en,int l,int r){
if (beg>=l && en<=r) return Min[node];
int mid = (beg+en)>>1,ans = 0x3f3f3f3f;
if (l<=mid) ans = min(ans,query(node<<1,beg,mid,l,r));
if (r>mid) ans = min(ans,query(node<<1|1,mid+1,en,l,r));
return ans;
}
} t;
struct ACAM{
int tr[N][26],fail[N],tot;
void insert(int id){
int len = strlen(s+1),now = 0;
for (int i=1;i<=len;i++){
int c = s[i]-'a';
if (!tr[now][c]){
tr[now][c] = ++tot;
val[tot] = (1ll*val[now]*26+c)%mod;
}
now = tr[now][c];
pre[id].push_back(now);
}
}
void build(){
for (int i=0;i<26;i++){
if (tr[0][i]){
q.push(tr[0][i]);
add(0,tr[0][i]);
}
}
int now;
while (!q.empty()){
now = q.front(),q.pop();
int fa = fail[now];
for (int i=0;i<26;i++){
if (!tr[now][i]) tr[now][i] = tr[fa][i];
else{
fail[tr[now][i]] = tr[fa][i];
add(tr[fa][i],tr[now][i]);
q.push(tr[now][i]);
}
}
}
}
} ac;
void dfs(int u,int fa){
col++;
int tmp = col;
ori[tmp] = u;
dfn[++cnt] = tmp;
beg[u] = cnt;
int v;
for (int i=head[u];i;i = edge[i].next){
v = edge[i].to;
if (v == fa) continue;
dfs(v,u);
dfn[++cnt] = tmp;
}
en[u] = cnt;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for (int i=1;i<=n;i++){
cin>>(s+1);
ac.insert(i);
}
ac.build();
dfs(0,-1);
t.build(1,1,cnt);
cin>>m;
int a,b,c,d,x,y,l,r;
for (int i=1;i<=m;i++){
cin>>a>>b>>c>>d;
x = pre[a][b-1],y = pre[c][d-1];
l = min(beg[x],beg[y]),r = max(en[x],en[y]);
cout<<val[ori[t.query(1,1,cnt,l,r)]]<<"\n";
}
return 0;
}

在 fail 树上跑树状数组

P2414 NOI2011 阿狸的打字机

题目有两个比较特殊的限制:一是每次只能添加或减少 $1$ 个字符,二是只有询问,而且询问是独立的。

我们先想一想如何回答询问。

比较暴力的方法是把 $y$ 放到 AC自动机上跑,每次跳 fail,看有多少次跳到了 $x$。

更具体一点,对每一个 $y$ 的节点,统计在其到根节点的路径上出现了 $x$ 的末尾节点的次数。

换一种表述,就是求 $x$ 节点的子树内,属于 $y$ 的节点的个数。

对每一个询问都跑一遍不是很现实,但是询问是独立的,也就是说处理询问的顺序和答案一点关系都没有,不妨离线下来。

而且,每次切换 $y$ 串的时候,需要修改很多不同的节点,相反,每次加一个字符,或删除一个字符,只需要修改一个节点。

可以以 $y$ 为第一关键字排序,边处理整个操作串边修改,修改次数为 $O(n)$ 级别。到了有询问的串时,就变成了经典的查询子树和的问题,可以把树拍扁,在 dfs 序上修改,最后区间求和,树状数组显然可以胜任这个工作。

总时间复杂度为 $O(n+m\log n)$。

Code

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
#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
const int N = 2e5+10;
int n,m,head[N],tot,dfn[N],cnt,l[N],r[N],ans[N],ori[N];
char s[N];
vector<pair<int,int> > a[N];
vector<int> exi[N];
queue<int> q;
struct e{
int next,to;
} edge[N*52];
void add(int x,int y){
edge[++tot].to = y;
edge[tot].next = head[x];
head[x] = tot;
}
struct BIT{
int tr[N*4];
void update(int x,int v){
for (;x<=cnt;x+=(x&(-x))) tr[x]+=v;
}
int query(int x){
int ans = 0;
for (;x;x-=(x&(-x))) ans+=tr[x];
return ans;
}
} tr1;
struct ACAM{
int tr[N][26],tot = 0,fa[N],fail[N];
void insert(){
int now = 0,cnt = 0;
for (int i=1;i<=n;i++){
if (s[i] == 'P') exi[now].pb(++cnt),ori[cnt] = now;
else if (s[i] == 'B') now = fa[now];
else{
int c = s[i]-'a';
if (!tr[now][c]){
tr[now][c] = ++tot;
fa[tot] = now;
}
now = tr[now][c];
}
}
}
void build(){
for (int i=0;i<26;i++){
if (tr[0][i]){
q.push(tr[0][i]);
add(0,tr[0][i]);
add(tr[0][i],0);
}
}
int now;
while (!q.empty()){
now = q.front(),q.pop();
int fai = fail[now];
for (int i=0;i<26;i++){
if (!tr[now][i]) tr[now][i] = tr[fai][i];
else{
fail[tr[now][i]] = tr[fai][i];
q.push(tr[now][i]);
add(tr[now][i],fail[tr[now][i]]);
add(fail[tr[now][i]],tr[now][i]);
}
}
}
}
void query(){
int now = 0;
for (int i=1;i<=n;i++){
if (s[i] == 'P'){
int tmp1,tmp2;
for (int x:exi[now]){
for (auto y:a[x]){
tmp1 = ori[y.first];
tmp2 = y.second;
ans[tmp2] = tr1.query(r[tmp1])-tr1.query(l[tmp1]-1);
}
}
}
else if (s[i] == 'B'){
tr1.update(l[now],-1);
now = fa[now];
}
else{
int c = s[i]-'a';
now = tr[now][c];
tr1.update(l[now],1);
}
}
}
} t;
void dfs(int u,int fa){
int v;
dfn[++cnt] = u;
l[u] = cnt;
for (int i=head[u];i;i = edge[i].next){
v = edge[i].to;
if (v == fa) continue;
dfs(v,u);
}
dfn[++cnt] = u;
r[u] = cnt;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>(s+1)>>m;
n = strlen(s+1);
int x,y;
for (int i=1;i<=m;i++){
cin>>x>>y;
a[y].pb(mp(x,i));
}
t.insert();
t.build();
dfs(0,-1);
t.query();
for (int i=1;i<=m;i++) cout<<ans[i]<<"\n";
return 0;
}