题目描述
题解
AC自动机模板题。
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
#define N 500005
char s[N*2];
int T,n,sz,ans;
int ch[N][30],is_end[N],fail[N];
bool vis[N];
queue <int> q;
void clear()
{
n=sz=ans=0;
memset(ch,0,sizeof(ch));memset(is_end,0,sizeof(is_end));
memset(fail,0,sizeof(fail));memset(vis,0,sizeof(vis));
}
void insert()
{
int len=strlen(s),now=0;
for (int i=0;i<len;++i)
{
int x=s[i]-'a';
if (!ch[now][x]) ch[now][x]=++sz;
now=ch[now][x];
}
++is_end[now];
}
void make_fail()
{
while (!q.empty()) q.pop();
for (int i=0;i<26;++i)
if (ch[0][i]) q.push(ch[0][i]);
while (!q.empty())
{
int now=q.front();q.pop();
for (int i=0;i<26;++i)
{
if (!ch[now][i])
{
ch[now][i]=ch[fail[now]][i];
continue;
}
fail[ch[now][i]]=ch[fail[now]][i];
q.push(ch[now][i]);
}
}
}
void ac()
{
int len=strlen(s),now=0;
for (int i=0;i<len;++i)
{
vis[now]=1;
int x=s[i]-'a';
int y=ch[now][x];
while (y&&!vis[y])
{
vis[y]=1;
ans+=is_end[y];
y=fail[y];
}
now=ch[now][x];
}
}
int main()
{
scanf("%d",&T);
while (T--)
{
clear();
scanf("%d\n",&n);
for (int i=1;i<=n;++i)
{
gets(s);
insert();
}
gets(s);
make_fail();
ac();
printf("%d\n",ans);
}
}