P3808 【模板】AC自动机(简单版)
题意
AC自动机模版题。
Code
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6+10;
int fail[maxn], e[maxn], tree[maxn][26], tot;
void insert(char *t) {
int p = 0;
for (int x, i=0; t[i]; ++i) {
x = t[i]-'a';
if(!tree[p][x]) tree[p][x] = ++tot;
p = tree[p][x];
}
++e[p];
}
void buildAc() {
queue<int> q;
for (int i=0; i<26; ++i) {
if(tree[0][i])
q.push(tree[0][i]);
}
while(!q.empty()) {
int u = q.front();
q.pop();
for (int i=0; i<26; ++i) {
if(tree[u][i]) fail[tree[u][i]] = tree[fail[u]][i], q.push(tree[u][i]);
else tree[u][i] = tree[fail[u]][i];
}
}
}
int query(char *t) {
int p=0, res=0;
for (int i=0; t[i]; ++i) {
p = tree[p][t[i]-'a'];
for (int i=p; i&&(~e[i]); i=fail[i]) res += e[i], e[i]=-1;
}
return res;
}
char str[maxn];
int main() {
int n;
scanf("%d", &n);
for (int i=1; i<=n; ++i) {
scanf("%s", str);
insert(str);
}
buildAc();
scanf("%s", str);
printf("%d\n", query(str));
return 0;
}