跳到正文

个人记录

AC自动机

laihaochen约 20 分钟
原文
文章信息与版本

文章信息

发布
2020年4月20日
收录
2026年1月8日
更新
2026年11月9日
篇幅
约 20 分钟

版本

  1. v2当前
  2. v1

目录

1. 引言

2. 构建字典树

3. 失配指针

4. 从字典树到字典图

5. 多模式匹配

6. 三道模板题

by laihaochen

1. 引言

前置知识:TrieTrie,kmpkmp

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

ACAC 自动机是一个以 TrieTrie 的结构为基础,结合 kmpkmp 的思想建立的。

建立一个 ACAC 自动机主要分为两个模块:

  • 构建字典树

  • 构造失配指针

2. 构建字典树

其实就是把模式串都丢进 TrieTrie 里,不过我们把 TrieTrie 中的从根到这个结点的字符串看作状态(从根到这个结点的字符串就是某个模式串的前缀),TrieTrie 中的边看作是不同状态的转移。

3. 失配指针

学过 kmpkmp 的 nextnext 指针可以知道,所谓 nextnext 指针,其目的就是减少无用的匹配次数,在失配指针中同样如此。

我们知道 nextnext 指针代表了最长的相同真前后缀,那么我们在失配指针是否也能找到与前后缀有关的定义呢?

fail[u]fail[u] 表示所有模式串的前缀中,匹配状态 uu 的最长后缀(不能为自己本身匹配自己)。

其实就是在一棵树上的 nextnext 指针。

如果看不太懂,可以看下面这幅图:

fail[6]fail[6] 表示所有模式串的前缀中,匹配状态 66 的最长后缀就是 11, 即字符串 s\mathtt{s}。简单来说,fail[u]fail[u] 就是任意一个状态,它的后缀最多能匹配状态 uu 多长,从这个角度来看就能理解为什么 fail[u]fail[u] 要这么定义吧。

3.1 构建指针

类似与 nextnext 指针,我们在求解 failfail 指针时,也是不断地向深度更浅的结点走,直到有满足的后缀。

假设现在遍历到的点是 uu,比它浅的所有点的 failfail 指针均以求得,且它的父亲 fafa 通过字符 cc 连接到它,即 tr[fa][c]=utr[fa][c] = u,我们进行如下的分类讨论:

  • 如果 tr[fail[fa]][c]tr[fail[fa]][c] 存在,那么我们直接在 fail[fa]fail[fa] 后沿着字符 cc 继续加一个字符 cc 就得到了 fail[u]fail[u] 所代表的状态。

  • 如果 tr[fail[fa]][c]tr[fail[fa]][c] 不存在,那么我们就像 nextnext 指针一样,一直找 tr[fail[fail[fa]]][c]tr[fail[fail[fa]]][c],重复 11,直到根节点。

下面的 gifgif 展示的是对于模式串 i\mathtt{i} he\mathtt{he} his\mathtt{his} she\mathtt{she} hers\mathtt{hers} 构建的字典树的求解 failfail 指针的过程:

  1. 黄色结点:当前结点 uu

  2. 绿色结点:已经遍历过的结点

  3. 橙色的边:failfail 指针

  4. 红色的边:当前 failfail 指针

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

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

4. 从字典树到字典图

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

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

C++
//这里以所有字符串都是由小写字母构成的举例
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];
			}
		}
	}
}

Q:Q: 为什么我们要以结点 00 作为根呢?

A:A: 因为这样的话,我们的 failfail 指针一开始直接默认指向结点 00 (fail(fail 初值为 0)0) 。

Q:Q: 为什么我们在 bfsbfs 前插入的是根结点的所有子结点,而非根结点呢?

A:A: 如果我们插入的是根结点,那么我们在第一次 bfsbfs 时,会将它们的 failfail 指针标记为自己。但是,根据 failfail 的定义,是不能自己匹配自己的,所以要插入的是根结点的所有子结点。

Q:Q: whilewhile 循环怎么不见了?

A:A: 因为我们在求 fail[tr[u][i]]fail[tr[u][i]] 时,已经求得了 fail[u]fail[u],所以在求 fail[u]fail[u] 时,已经把之前得循环都走完了,故只需赋值为 tr[fail[u]][i]tr[fail[u]][i] 即可。

Q:Q: 为什么我们在 tr[u][i]tr[u][i] 不存在时,要把它赋值为 tr[fail[u]][i]tr[fail[u]][i] 呢?这样不是破坏了字典树的结构了吗?

A:A: 我们考虑何时会用到 tr[u][i]tr[u][i]:

肯定是存在一个状态 vv,fail[fa]=ufail[fa] = u 而且 tr[fa][i]=vtr[fa][i] = v

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

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

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

  1. 蓝色结点:bfsbfs 遍历到的结点 uu

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

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

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

  5. 黄色的边:failfail 指针

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

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

5. 多模式匹配

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

C++
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;
}

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

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

6. 三道模板题

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

C++
#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(tlen∗max slen+∑slen)O(t_{len} * max ~ s_{len} + \sum s_{len})

C++
#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自动机(二次加强版)

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

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

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

可以得出代码:

C++
#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;
}

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

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

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

C++
#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;
}

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

原文
存档评论1 条抓取于