AC自动机

· · 个人记录

目录

1. 引言

2. 构建字典树

3. 失配指针

4. 从字典树到字典图

5. 多模式匹配

6. 三道模板题

by laihaochen

1. 引言

前置知识:Trie,kmp

解决字符串问题时,如果是单模式串匹配,可以使用 kmp;在进行字符串查找时,我们可以使用 Trie ;那么我们在多模式串匹配时就要使用到 AC 自动机。

建立一个 $AC$ 自动机主要分为两个模块: - 构建字典树 - 构造失配指针 ## 2. 构建字典树 其实就是把模式串都丢进 $Trie$ 里,不过我们把 $Trie$ 中的从根到这个结点的字符串看作状态(从根到这个结点的字符串就是某个模式串的前缀),$Trie$ 中的边看作是不同状态的转移。 ## 3. 失配指针 学过 $kmp$ 的 $next$ 指针可以知道,所谓 $next$ 指针,其目的就是减少无用的匹配次数,在失配指针中同样如此。 我们知道 $next$ 指针代表了最长的相同真前后缀,那么我们在失配指针是否也能找到与前后缀有关的定义呢? $fail[u]$ 表示所有模式串的前缀中,匹配状态 $u$ 的最长后缀(不能为自己本身匹配自己)。 其实就是在一棵树上的 $next$ 指针。 如果看不太懂,可以看下面这幅图: $fail[6]$ 表示所有模式串的前缀中,匹配状态 $6$ 的最长后缀就是 $1$, 即字符串 $\mathtt{s}$。简单来说,$fail[u]$ 就是任意一个状态,它的后缀最多能匹配状态 $u$ 多长,从这个角度来看就能理解为什么 $fail[u]$ 要这么定义吧。 ![](https://oi-wiki.org/string/images/ac-automaton1.png) ### 3.1 构建指针 类似与 $next$ 指针,我们在求解 $fail$ 指针时,也是不断地向深度更浅的结点走,直到有满足的后缀。 假设现在遍历到的点是 $u$,比它浅的所有点的 $fail$ 指针均以求得,且它的父亲 $fa$ 通过字符 $c$ 连接到它,即 $tr[fa][c] = u$,我们进行如下的分类讨论: - 如果 $tr[fail[fa]][c]$ 存在,那么我们直接在 $fail[fa]$ 后沿着字符 $c$ 继续加一个字符 $c$ 就得到了 $fail[u]$ 所代表的状态。 - 如果 $tr[fail[fa]][c]$ 不存在,那么我们就像 $next$ 指针一样,一直找 $tr[fail[fail[fa]]][c]$,重复 $1$,直到根节点。 下面的 $gif$ 展示的是对于模式串 $\mathtt{i}$ $\mathtt{he}$ $\mathtt{his}$ $\mathtt{she}$ $\mathtt{hers}$ 构建的字典树的求解 $fail$ 指针的过程: 1. 黄色结点:当前结点 $u
  1. 绿色结点:已经遍历过的结点

  2. 橙色的边:fail 指针

  3. 红色的边:当前 fail 指针

我们来分析一下求解 fail[6] 的过程:

首先找到 6 的父结点 5,已知 fail[5] = 10 。然而结点 10 并没有 s 连出的边,所以继续找到 fail[10] = 0,发现结点 0 有 s 连出的边,指向结点 7 。故 fail[6] = 7 。

4. 从字典树到字典图

基本上就可以写出构建字典树以及求解 fail 指针的代码:

我们用 bfs 遍历,求 fail 指针,因为我们要在深的结点时,用到浅的结点的信息。

//这里以所有字符串都是由小写字母构成的举例
void update (char *s) {//构建字典树
    int len = strlen(s + 1), u = 0;
    for (int i = 1; i <= len; i++) {
        if (!tr[u][s[i] - 'a']) {
            tr[u][s[i] - 'a'] = ++num;
        }
        u = tr[u][s[i] - 'a'];
    }
    ed[u]++;
}
void build () {//求解fail指针
    for (int i = 0; i < 26; i++) {
        if (tr[0][i]) {
            q.push(tr[0][i]);
        }
    }
    while (!q.empty()) {
        int u = q.front();//fail[u]已知,要求fail[tr[u][i]]
        q.pop();
        for (int i = 0; i < 26; i++) {
            if (tr[u][i]) {
                fail[tr[u][i]] = tr[fail[u]][i];
                q.push(tr[u][i]);
            } else {
                tr[u][i] = tr[fail[u]][i];
            }
        }
    }
}
$A:$ 因为这样的话,我们的 $fail$ 指针一开始直接默认指向结点 $0$ $(fail$ 初值为 $0)$ 。 $Q:$ 为什么我们在 $bfs$ 前插入的是根结点的所有子结点,而非根结点呢? $A:$ 如果我们插入的是根结点,那么我们在第一次 $bfs$ 时,会将它们的 $fail$ 指针标记为自己。但是,根据 $fail$ 的定义,是不能自己匹配自己的,所以要插入的是根结点的所有子结点。 $Q:$ $while$ 循环怎么不见了? $A:$ 因为我们在求 $fail[tr[u][i]]$ 时,已经求得了 $fail[u]$,所以在求 $fail[u]$ 时,已经把之前得循环都走完了,故只需赋值为 $tr[fail[u]][i]$ 即可。 $Q:$ 为什么我们在 $tr[u][i]$ 不存在时,要把它赋值为 $tr[fail[u]][i]$ 呢?这样不是破坏了字典树的结构了吗? $A:$ 我们考虑何时会用到 $tr[u][i]$: 肯定是存在一个状态 $v$,$fail[fa] = u$ 而且 $tr[fa][i] = v

那么如果我们不赋值,按照代码,它会找到 tr[fail[fail[fa]]][i] 也就是 tr[fail[u]][i],再进行判断。

那么我们直接把 tr[u][i] 赋值为 tr[fail[u]][i] 其实就是为了节省这里跳转的时间,有点像并查集的路径压缩的思路。

我们将之前的 gif 修改一下:

  1. 蓝色结点:bfs 遍历到的结点 u

  2. 蓝色的边:当前结点下,AC 自动机修改字典树结构连出的边

  3. 黑色的边:AC 自动机修改字典树结构连出的边

  4. 红色的边:当前结点求出的 fail 指针

  5. 黄色的边:fail 指针

  6. 灰色的边:字典树的边

我们把现在形成的图叫做字典图。

5. 多模式匹配

这里我们假设一个模式串能匹配一次。

int query (char *s) {
    int u = 0, res = 0, len = strlen (s + 1);
    for (int i = 1; i <= len; i++) {
        u = tr[u][s[i] - 'a'];
        for (int j = u; j != 0 && end[j] != -1; j = fail[j]) {
            res += ed[j];
            ed[j] = -1;//匹配过就打个标记
        }
    }
    return res;
}

应该还是很好理解的吧,跟 kmp 很像。

因为每个点最多遍历一次,所以时间复杂度是 O(t_{len} + \sum s_{len}) (t 为文本串,\sum s_{len} 为模式串长度之和)。

6. 三道模板题

P3808 【模板】AC自动机(简单版)

#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6 + 5;
int n, num, tr[N][30], ed[N], fail[N];
char c[N];
queue <int> q;
void update (char *s) {
    int len = strlen(s + 1), u = 0;
    for (int i = 1; i <= len; i++) {
        if (!tr[u][s[i] - 'a']) {
            tr[u][s[i] - 'a'] = ++num;
        }
        u = tr[u][s[i] - 'a'];
    }
    ed[u]++;
}
void build () {
    for (int i = 0; i < 26; i++) {
        if (tr[0][i]) {
            q.push(tr[0][i]);
        }
    }
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int i = 0; i < 26; i++) {
            if (tr[u][i]) {
                fail[tr[u][i]] = tr[fail[u]][i];
                q.push(tr[u][i]);
            } else {
                tr[u][i] = tr[fail[u]][i];
            }
        }
    }
}
int query (char *s) {
    int u = 0, res = 0, len = strlen (s + 1);
    for (int i = 1; i <= len; i++) {
        u = tr[u][s[i] - 'a'];
        for (int j = u; j != 0 && ed[j] != -1; j = fail[j]) {
            res += ed[j];
            ed[j] = -1;
        }
    }
    return res;
}
int main() {
    scanf ("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf ("%s", c + 1);
        update (c);
    }
    build();
    scanf ("%s", c + 1);
    printf ("%d\n", query(c));
    return 0;
} 

P3796 【模板】AC自动机(加强版)

因为一个模式串可能匹配多次,所以多模式匹配时,每次都可能要遍历最长的模式串的长度,故时间复杂度为:O(t_{len} * max ~ s_{len} + \sum s_{len})

#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 10505, L = 1e6 + 5;
int n, num, tr[N][30], ed[N], cnt[N], fail[N];
char c[155][75], s[L];
queue <int> q;
void update (char *s, int id) {//第id个模式串
    int u = 0, len = strlen (s + 1);
    for (int i = 1; i <= len; i++) {
        if (!tr[u][s[i] - 'a']) {
            tr[u][s[i] - 'a'] = ++num;
        }
        u = tr[u][s[i] - 'a'];
    }
    ed[u] = id;
}
void build () {
    for (int i = 0; i < 26; i++) {
        if (tr[0][i]) {
            q.push(tr[0][i]);
        }
    }
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int i = 0; i < 26; i++) {
            if (tr[u][i]) {
                fail[tr[u][i]] = tr[fail[u]][i];
                q.push(tr[u][i]);
            } else {
                tr[u][i] = tr[fail[u]][i];
            }
        }
    }
}
int query (char *s) {
    int len = strlen (s + 1), u = 0, res = 0;
    for (int i = 1; i <= len; i++) {
        u = tr[u][s[i] - 'a'];
        for (int j = u; j != 0; j = fail[j]) {
            cnt[ed[j]]++;//记录每个模式串出现几次即可。
        }
    }
    for (int i = 1; i <= n; i++) {
        res = max (res, cnt[i]);
    }
    return res;
}
inline void init() {
    num = 0;
    memset (tr, 0, sizeof(tr));
    memset (ed, 0, sizeof(ed));
    memset (cnt, 0, sizeof(cnt));
    memset (fail, 0, sizeof(fail));
    while (!q.empty()) {
        q.pop();
    }
}
int main() {
    while (1) {//多组数据
        scanf ("%d", &n);
        if (n == 0) {
            break;
        }
        init();
        for (int i = 1; i <= n; i++) {
            scanf ("%s", c[i] + 1);
            update (c[i], i);
        }
        build();
        scanf ("%s", s + 1);
        int x = query (s);
        printf ("%d\n", x);
        for (int i = 1; i <= n; i++) {
            if (cnt[i] == x) {
                printf ("%s\n", c[i] + 1);
            }
        }
    }
    return 0;
}

P5357 【模板】AC自动机(二次加强版)

相较于加强版,这题如果出现了相同的模式串会影响答案。

因为在给 end 赋值时,只会赋值为最新的 id,所以前面的就没有对应的 end 了。

那么我们 end 只赋值为第一个 id,剩下的都用 idx 转换到第一个。( idx[i] 表示第 i 个模式串第一次出现的 end )

可以得出代码:

#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 2e5 + 5, L = 2e6 + 5;
int n, num, tr[N][30], ed[N], idx[N], fail[N], cnt[N];
char c[N], s[L];
queue <int> q;
void update (char *s, int id) {
    int u = 0, len = strlen (s + 1);
    for (int i = 1; i <= len; i++) {
        if (!tr[u][s[i] - 'a']) {
            tr[u][s[i] - 'a'] = ++num;
        }
        u = tr[u][s[i] - 'a'];
    }
    //重复的单词会有影响
    //idx[i]表示第i个模式串第一次出现的结尾 
    if (ed[u]) {//出现过 
        idx[id] = ed[u];
    } else {//没有出现过 
        idx[id] = ed[u] = id;
    }
}
void build () {
    for (int i = 0; i < 26; i++) {
        if (tr[0][i]) {
            q.push(tr[0][i]);
        }
    }
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int i = 0; i < 26; i++) {
            if (tr[u][i]) {
                fail[tr[u][i]] = tr[fail[u]][i];
                q.push(tr[u][i]);
            } else {
                tr[u][i] = tr[fail[u]][i];
            }
        }
    }
}
void query (char *s) {
    int len = strlen (s + 1), u = 0, res = 0;
    for (int i = 1; i <= len; i++) {
        u = tr[u][s[i] - 'a'];
        for (int j = u; j != 0; j = fail[j]) {
            cnt[ed[j]]++;
        }
    }
}
int main() {
    scanf ("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf ("%s", c + 1);
        update (c, i);
    }
    build();
    scanf ("%s", s + 1);
    query (s);
    for (int i = 1; i <= n; i++) {
        printf ("%d\n", cnt[idx[i]]);
    }
    return 0;
}

但只有 76 分,我们发现这题没有限制模式串的最大长度,也就是说,我们这个算法最高的时间复杂度为:O(2e5 * 2e5 = 4e10) 肯定超了。

那么我们怎么能使 Trie 上的每一个点都只经过一次呢?

我们发现每次匹配模式串时,可能会有一个较深的点被用到了好多次,例如结点 4,在结点 7 与结点 9 时都会被用到,那么我们其实可以保存下每个点被访问了几次,最后再加起来。我们可以用拓扑排序来实现这个操作。

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 2e5 + 5, L = 2e6 + 5;
int n, num, rd[N], ans[N], tr[N][30], ed[N], idx[N], fail[N], cnt[N];
char c[N], s[L];
queue <int> q;
void update (char *s, int id) {
    int u = 0, len = strlen (s + 1);
    for (int i = 1; i <= len; i++) {
        if (!tr[u][s[i] - 'a']) {
            tr[u][s[i] - 'a'] = ++num;
        }
        u = tr[u][s[i] - 'a'];
    }
    if (ed[u]) {
        idx[id] = ed[u];
    } else {
        idx[id] = ed[u] = id;
    }
}
void build () {
    for (int i = 0; i < 26; i++) {
        if (tr[0][i]) {
            q.push(tr[0][i]);
        }
    }
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int i = 0; i < 26; i++) {
            if (tr[u][i]) {
                fail[tr[u][i]] = tr[fail[u]][i];
                rd[tr[fail[u]][i]]++;
                q.push(tr[u][i]);
            } else {
                tr[u][i] = tr[fail[u]][i];
            }
        }
    }
}
void query (char *s) {
    int len = strlen (s + 1), u = 0, res = 0;
    for (int i = 1; i <= len; i++) {
        u = tr[u][s[i] - 'a'];
        ans[u]++;
    }
}
void topu () {
    while (!q.empty()) {
        q.pop();
    }
    for (int i = 1; i <= num; i++) {
        if (!rd[i]) {
            q.push(i);
        }
    }
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        cnt[ed[u]] = ans[u]; 
        int v = fail[u];
        rd[v]--;
        ans[v] += ans[u];//深的点更新浅的点
        if (!rd[v]) {
            q.push(v);
        }
    }
}
int main() {
    scanf ("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf ("%s", c + 1);
        update (c, i);
    }
    build();
    scanf ("%s", s + 1);
    query (s);
    topu();
    for (int i = 1; i <= n; i++) {
        printf ("%d\n", cnt[idx[i]]);
    }
    return 0;
}

附:gif 与部分图片来自 oi-wiki