AC自动机的裸题,不过需要注意几个地方,keywords中有重复的,而且模板中会重复出现keywords~
#include <cstdio>
#include <queue>
#define SIGMA_SIZE 26
#define MAXNODE 500100
using namespace std;
int ch[MAXNODE][SIGMA_SIZE];
int f[MAXNODE]; // fail函数
int val[MAXNODE]; // 每个字符串的结尾结点都有一个非0的val
int last[MAXNODE]; // 输出链表的下一个结点
int sz;
int vis[MAXNODE];
char key[10100];
char mod[1000020];
int N,t;
int ans;
void init()
{
sz = 1;
memset(ch[0], 0, sizeof(ch[0]));
memset(vis, 0, sizeof(vis));
}
// 字符c的编号
int idx(char c)
{
return c-'a';
}
// 插入字符串。v必须非0
void insert(char *s, int v)
{
int i;
int u = 0, n = strlen(s);
for(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 print(int j)
{
if(j)
{
if(!vis[j])
{
vis[j]=1;
ans+=val[j];
}
print(last[j]);
}
}
// 在T中找模板
void find(char* T)
{
int n = strlen(T);
int j = 0; // 当前结点编号,初始为根结点
for(int i = 0; i < n; i++)
{ // 文本串当前指针
int c = idx(T[i]);
while(j && !ch[j][c]) j = f[j]; // 顺着失配边走,直到可以匹配
j = ch[j][c];
if(val[j]) print(j);
else if(last[j]) print(last[j]); // 找到了!
}
}
// 计算fail函数
void getFail()
{
queue<int> q;
f[0] = 0; // 初始化队列
for(int c = 0; c < SIGMA_SIZE; c++)
{
int u = ch[0][c];
if(u) { f[u] = 0; q.push(u); last[u] = 0; }
}
while(!q.empty()) // 按BFS顺序计算fail
{
int r = q.front(); q.pop();
for(int c = 0; c < SIGMA_SIZE; c++)
{
int u = ch[r][c];
if(!u) continue;
q.push(u);
int v = f[r];
while(v && !ch[v][c]) v = f[v];
f[u] = ch[v][c];
last[u] = val[f[u]] ? f[u] : last[f[u]];
}
}
}
int main()
{
int i;
scanf("%d",&t);
while(t--)
{
init();
for(i=0;i<MAXNODE;i++) val[i]=0;
ans=0;
scanf("%d",&N);
for(i=1;i<=N;i++)
{
scanf("%s",key);
insert(key,1);
}
scanf("%s",mod);
getFail();
find(mod);
printf("%d\n",ans);
}
return 0;
}