帮我写一个ac自动机的模板
时间: 2023-08-20 21:37:14 浏览: 145
AC自动机_AC自动机模板_
好的,以下是 AC 自动机的模板代码:
```C++
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 100010;
const int MAXM = 26;
struct TrieNode {
int fail;
int next[MAXM];
int cnt;
} trie[MAXN];
int nodeCnt;
void insertTrie(char* str) {
int cur = 0;
for (int i = 0; str[i]; i++) {
int t = str[i] - 'a';
if (!trie[cur].next[t]) {
trie[cur].next[t] = ++nodeCnt;
}
cur = trie[cur].next[t];
}
trie[cur].cnt++;
}
void buildAC() {
queue<int> q;
for (int i = 0; i < MAXM; i++) {
if (trie[0].next[i]) {
q.push(trie[0].next[i]);
}
}
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int i = 0; i < MAXM; i++) {
if (trie[cur].next[i]) {
int fail = trie[cur].fail;
while (fail && !trie[fail].next[i]) {
fail = trie[fail].fail;
}
trie[trie[cur].next[i]].fail = trie[fail].next[i];
q.push(trie[cur].next[i]);
}
}
}
}
int queryAC(char* str) {
int cur = 0, res = 0;
for (int i = 0; str[i]; i++) {
int t = str[i] - 'a';
while (cur && !trie[cur].next[t]) {
cur = trie[cur].fail;
}
cur = trie[cur].next[t];
int tmp = cur;
while (tmp && trie[tmp].cnt != -1) {
res += trie[tmp].cnt;
trie[tmp].cnt = -1;
tmp = trie[tmp].fail;
}
}
return res;
}
int main() {
int n;
char str[MAXN];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> str;
insertTrie(str);
}
buildAC();
cin >> str;
cout << queryAC(str) << endl;
return 0;
}
```
这个模板实现了 AC 自动机的构建和查询功能,可以在其中插入多个字符串,然后查询一个字符串中有多少个字符串在之前插入的字符串中出现过。
阅读全文