终于写出来了传说中的AC自动机,听起来这个名字就非常的吉利,AC啊……此版本AC自动机是照着佳哥的《训练指南》写的,实现的功能是查找主串种出现了多少种模式串。AC自动机简单来说就是在字典树上指失配指针,然后进行匹配,当然,我这个AC自动机是有了Trie图的,效率能更高一些。
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int ans = 0;
struct ACautomata{
int ch[500001][27], val[500001];
int f[500010], sz;
void reset(){
memset(ch[0], 0, sizeof(ch[0]));
memset(val, 0, sizeof(val));
sz = 1;
}
int idx(char c){
return c - 'a';
}
void insert(char *s, int v){
int u = 0, n = strlen(s);
for (int i = 0; i < n; i++){
int c = idx(s[i]);
if (!ch[u][c]){
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] = v;
}
void getfail(){
queue<int> q;
f[0] = 0;
for (int c = 0; c < 26; c++){
int u = ch[0][c];
if (u){f[u] = 0; q.push(u);}
}
while(!q.empty()){
int r = q.front(); q.pop();
for (int c = 0; c < 26; c++){
int u = ch[r][c];
if (!u){ch[r][c] = ch[f[r]][c]; continue;}
q.push(u);
int v = f[r];
while(v && !ch[v][c]) v = f[v];
f[u] = ch[v][c];
}
}
}
void find(char *T){
int n = strlen(T);
int j = 0;
for (int i = 0; i < n; i++){
int c = idx(T[i]);
j = ch[j][c];
int tmp = j;
while(tmp && val[tmp]){
ans += 1;
val[tmp] = 0;
tmp = f[tmp];
}
}
}
}ac;
char s[55], ss[11111];
int main(){
int t;
ac.reset();
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
while (n--){
scanf("%s", s);
ac.insert(s, 1);
}
ac.getfail();
scanf("%s", ss);
ans = 0;
ac.find(ss);
printf("%d\n", ans);
}
}