跳到正文

个人记录

AC 自动机模板

EuphoricStar约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年8月1日
更新
2026年8月1日
篇幅
约 3 分钟

版本

  1. v1当前

注:这份代码同时也是 P3808 【模板】AC自动机(简单版) 的 AC 代码。

C++
#include <bits/stdc++.h>
using namespace std;

const int maxn = 1000100;

int n;
struct AC {
	int ch[maxn][26], tot, cnt[maxn], fail[maxn];
	
	void init() {
		tot = 0;
		memset(ch, 0, sizeof(ch));
		memset(cnt, 0, sizeof(cnt));
		memset(fail, 0, sizeof(fail));
	}
	
	void insert(char *str) {
		int p = 0;
		for (int i = 0; str[i]; ++i) {
			if (!ch[p][str[i] - 'a']) {
				ch[p][str[i] - 'a'] = ++tot;
			}
			p = ch[p][str[i] - 'a'];
		}
		++cnt[p];
	}
	
	void build() {
		queue<int> q;
		for (int i = 0; i < 26; ++i) {
			if (ch[0][i]) {
				q.push(ch[0][i]);
			}
		}
		while (q.size()) {
			int u = q.front();
			q.pop();
			for (int i = 0; i < 26; ++i) {
				if (ch[u][i]) {
					fail[ch[u][i]] = ch[fail[u]][i];
					q.push(ch[u][i]);
				} else {
					ch[u][i] = ch[fail[u]][i];
				}
			}
		}
	}

	int query(char *str) {
		int p = 0, res = 0;
		for (int i = 0; str[i]; ++i) {
			p = ch[p][str[i] - 'a'];
			for (int j = p; j && ~cnt[j]; j = fail[j]) {
				res += cnt[j];
				cnt[j] = -1;
			}
		}
		return res;
	}
} solver;

int main() {
	solver.init();
	char s[maxn];
	scanf("%d", &n);
	for (int i = 0; i < n; ++i) {
		scanf("%s", s);
		solver.insert(s);
	}
	solver.build();
	scanf("%s", s);
	printf("%d", solver.query(s));
	return 0;
}
原文
存档评论3 条抓取于