ac自动机入门,基础模板
先看的白书,没看懂。
再找的大牛模板,虽然慢了点,好歹看懂了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int sigma_size = 28;
const int maxnode = 500005;
struct Trie{
int ch[maxnode][sigma_size];
int val[maxnode];
int f[maxnode];
int root,L;
int newnode(){
for(int i = 0;i < sigma_size;i++){
ch[L][i] = -1;
}
val[L++] = 0;
return L - 1;
}
void init()
{
L = 0;
root = newnode();
}
int idx(char x){
return x - 'a';
}
void Insert(char *s){
int len = strlen(s);
int now = root;
for(int i = 0;i < len;i++){
int c = idx(s[i]);
if(ch[now][c] == -1){
ch[now][c] = newnode();
}
now = ch[now][c];
}
val[now]++;
}
void getFail(){
queue<int> q;
f[root] = root;
for(int i = 0;i < sigma_size;i++){
if(ch[root][i] == -1){
ch[root][i] = root;
}
else {
f[ch[root][i]] = root;
q.push(ch[root][i]);
}
}
while(!q.empty()){
int now = q.front();q.pop();
for(int i = 0;i < sigma_size;i++){
if(ch[now][i] == -1){
ch[now][i] = ch[f[now]][i];
}
else
{
f[ch[now][i]] = ch[f[now]][i];
q.push(ch[now][i]);
}
}
}
}
int Find(char *s){
int len = strlen(s);
int now = root;
int res = 0;
for(int i = 0;i < len;i++){
int c = idx(s[i]);
now = ch[now][c];
int tmp = now;
while(tmp != root){
res += val[tmp];
val[tmp] = 0;
tmp = f[tmp];
}
}
return res;
}
};
Trie ac;
char buf[1000020];
int main()
{
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
ac.init();
while(n--){
scanf("%s",buf);
ac.Insert(buf);
}
ac.getFail();
scanf("%s",buf);
int ans = ac.Find(buf);
printf("%d\n",ans);
}
return 0;
}