跳到正文

算法·理论

AC自动机(原文)

Gyf117约 11 分钟
原文

这是 2026年9月19日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年8月26日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 11 分钟

版本

  1. v3当前
  2. v2
  3. v1

AC自动机

AC自动机是用于计算多个模式串在一个文本串里分别出现了几次的一种算法.

AC自动机是在trie上通过失配指针failfail(以下写作ff)实现的.


建树

用模式串建树就不说了.

构建失配指针

失配指针指向当前匹配失败时回到哪里继续匹配. 此时显然要找到在树上的非本身的最长后缀.

这里设ii为当前要找失配指针的节点, pip_i为ii的父节点, 此时pip_i对应的字符串的最长后缀为fpif_{p_i}.只需要判断fpif_{p_i}是否有相同字符的儿子.

若有, 则连一条失配指针, 否则失配指针指向根(因为此时没有后缀).

放一张图(绿色表示失配指针)

然而有反例, 因为根节点不存在在树上的非本身的最长后缀(空串没有非本身的后缀), 所以深度为11的串不能正确找到失配指针(根),而找到自己.

所以进行预处理深度为11的串.

同时更深的点要比更浅的点更晚更新.(记住这句话)

所以用bfs.

同时为了方便实现, 让父亲帮儿子找失配指针.

考虑到在ii失配时还要往fif_i退再匹配, 所以从ii连一条边到fif_i的儿子.

放一张图(绿色表示失配指针, 红色表示新连的边)

查询

如果走到了一个点就直接暴力跳失配指针统计答案.

代码

这里给出 @2huk 大蛇的P3796代码 orz

C++
#include <bits/stdc++.h>

using namespace std;

const int N = 70 * 150 * 26 + 10;

int n, res[N];
string s[N], t;

struct AC {
	int idx;
	int tr[N][26];
	int f[N];
	int st[N];
	
	void clear() {
		for (int i = 0; i <= idx; ++ i )
			for (int j = 0; j < 26; ++ j ) tr[i][j] = 0;
		idx = 0;
		memset(f, 0, sizeof f);
		memset(st, 0, sizeof st);
	}
	
	void modify(string s, int id) {
		int p = 0;
		for (char c : s) {
			int w = c - 'a';
			if (!tr[p][w]) tr[p][w] = ++ idx;
			p = tr[p][w];
		}
		st[p] = id;
	}
	
	void build() {
		queue<int> q;
		for (int i = 0; i < 26; ++ i )
			if (tr[0][i]) {
				q.push(tr[0][i]);
				f[tr[0][i]] = 0;
			}
		
		while (q.size()) {
			int u = q.front();
			q.pop();
			for (int i = 0; i < 26; ++ i ) {
				if (tr[u][i]) {
					f[tr[u][i]] = tr[f[u]][i];
					q.push(tr[u][i]);
				} else {
					tr[u][i] = tr[f[u]][i];
				}
			}
		}
	}
	
	void query(string t) {
		int p = 0;
		for (char c : t) {
			int w = c - 'a';
			p = tr[p][w];
			for (int q = p; q; q = f[q])
				res[st[q]] ++ ;
		}
	}
}T;

void solve() {
	T.clear();
	
	for (int _ = 1; _ <= n; ++ _ ) {
		cin >> s[_];
		T.modify(s[_], _);
	}
	
	memset(res, 0, sizeof res);
	cin >> t;
	T.build();
	T.query(t);
	
	vector<int> ans;
	int mx = -1;
	for (int i = 1; i <= n; ++ i ) {
		if (res[i] > mx) {
			mx = res[i];
			ans = {i};
		} else if (res[i] == mx) {
			ans.push_back(i);
		}
	}
	
	cout << mx << '\n';
	for (int v : ans) cout << s[v] << '\n';
}

signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	while (cin >> n, n) solve();
	return 0;
}

优化

显然, 暴力跳失配指针会被类似一条链卡成O(n2)\text{O}\left(n^2\right), 所以打一个tag存储起来.

最后跑一遍拓扑排序统一统计, 复杂度O(n)\text{O}\left(n\right).

代码

依旧给出 @2huk 大蛇的P5357代码 orz

C++
#include <bits/stdc++.h>

using namespace std;

const int N = 2e5 + 10;

int n, res[N];
string s[N], t;

struct AC {
	int tr[N][26], idx, cnt[N];
	vector<int> id[N];		// 哪些模式串以这个点结尾
	int f[N];
	vector<int> g[N];
	int d[N], tag[N];
	
	void modify(string s, int i) {
		int p = 0;
		for (char _ : s) {
			int w = _ - 'a';
			if (!tr[p][w]) tr[p][w] = ++ idx;
			p = tr[p][w];
		}
		id[p].push_back(i);
	}
	
	void build() {
		queue<int> q;
		for (int i = 0; i < 26; ++ i )
			if (tr[0][i]) {
				f[tr[0][i]] = 0;
				q.push(tr[0][i]);
			}
		
		while (q.size()) {
			int u = q.front();
			q.pop();
			for (int i = 0; i < 26; ++ i ) {
				if (tr[u][i]) {
					f[tr[u][i]] = tr[f[u]][i];
					d[f[tr[u][i]]] ++ ;
					q.push(tr[u][i]);
				} else {
					tr[u][i] = tr[f[u]][i];
				}
			}
		}
	}
	
	void query(string t) {
		int p = 0;
		for (char _ : t) {
			int w = _ - 'a';
			p = tr[p][w];
			tag[p] ++ ;
		}
	}
	
	void topo() {
		queue<int> q;
		for (int i = 1; i <= idx; ++ i )
			if (!d[i]) q.push(i);
		while (q.size()) {
			int u = q.front();
			q.pop();
			
			int v = f[u];
			tag[v] += tag[u];
			if (! -- d[v]) q.push(v);
		}
		
		for (int i = 1; i <= idx; ++ i )
			for (int j : id[i]) res[j] += tag[i];
	}
}T;

signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; ++ i ) {
		cin >> s[i];
		T.modify(s[i], i);
	}
	T.build();
	cin >> t;
	T.query(t);
	T.topo();
	for (int i = 1; i <= n; ++ i ) cout << res[i] << '\n';
	return 0;
}

优化

你没看错, 还能优化, 失配指针一定从更深的点指向更浅的点, 而在「构建失配指针」里, 我们提到了更深的点要比更浅的点更晚更新.

所以将bfn翻转其实就是拓扑序. 常数显然比 queue 小.

代码

idea bye Gyf117 code by 2huk

C++
#include <bits/stdc++.h>

using namespace std;

const int N = 2e5 + 10;

int n, res[N];
string s[N], t;

struct AC {
	int tr[N][26], idx;
	int f[N];
	int d[N], tag[N];
	int q[N], l = 1, r;
	vector<int> id[N];
	
	void modify(string s, int i) {
		int p = 0;
		for (char _ : s) {
			int w = _ - 'a';
			if (!tr[p][w]) tr[p][w] = ++ idx;
			p = tr[p][w];
		}
		id[p].push_back(i);
	}
	
	
	void build() {
		for (int i = 0; i < 26; ++ i )
			if (tr[0][i]) {
				q[ ++ r] = tr[0][i];
			}
		
		while (l <= r) {
			int u = q[l ++ ];
			for (int i = 0; i < 26; ++ i ) {
				if (tr[u][i]) {
					f[tr[u][i]] = tr[f[u]][i];
					q[ ++ r] = tr[u][i];
				} else {
					tr[u][i] = tr[f[u]][i];
				}
			}
		}
	}
	
	void query(string t) {
		int p = 0;
		for (char _ : t) {
			int w = _ - 'a';
			p = tr[p][w];
			tag[p] ++ ;
		}
	}
	
	void work() {
		for (int i = r; i; -- i ) {
			int x = q[i], y = f[x];
			tag[y] += tag[x];
		}
		
		for (int i = 1; i <= idx; ++ i )
			for (int j : id[i]) res[j] += tag[i];
	}
} T;

signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; ++ i ) {
		cin >> s[i];
		T.modify(s[i], i);
	}
	T.build();
	cin >> t;
	T.query(t);
	T.work();
	for (int i = 1; i <= n; ++ i ) cout << res[i] << '\n';
	return 0;
}