单词查询
题目
解析
AC自动机,顾名思义,就是能自动AC
前置知识:KMP,trie
众所周知,当只有一个串时,可以使用KMP来解决这个问题
但是,当有多个串时,文本串会匹配n次,继而产生
O
(
n
m
)
O(nm)
O(nm)的复杂度
那么我们考虑用一些奇奇怪怪的数据结构来解决这个问题,而单论存储,显然trie是最优的
插入完后考虑查询,首先需要预处理
n
x
t
nxt
nxt,为了同时匹配多个模式串,我们需要使得
n
x
t
nxt
nxt可以跨模式串转换
于是我们考虑使用一个BFS处理,然后要利用trie的性质,加上跳转移边优化(事实上优化后叫trie图)
之后的查询就很简单了
记得清空数组
code:
#include<queue>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
struct AC_easy
{
int tot,ch[1000010][26],nxt[1000010],val[1000010],k;
queue <int> b;
inline void build(){tot=1,nxt[1]=0,memset(ch[1],0,sizeof(ch[1]));while(b.size())b.pop();}
inline void insert(char *s)
{
int len=strlen(s),now=1;
for(int i=0;i<len;++i)
{
if(!ch[now][s[i]-'a'])ch[now][s[i]-'a']=++tot,memset(ch[tot],0,sizeof(ch[tot])),val[tot]=0;
now=ch[now][s[i]-'a'];
}
val[now]++;
}
inline void bfs()
{
for(int i=0;i<=25;++i)ch[0][i]=1;
b.push(1);
while(!b.empty())
{
k=b.front(),b.pop();
for(int i=0;i<=25;++i)
{
if(!ch[k][i])ch[k][i]=ch[nxt[k]][i];
else nxt[ch[k][i]]=ch[nxt[k]][i],b.push(ch[k][i]);
}
}
}
inline int query(char *s)
{
int now=1,ans=0,len=strlen(s),q;
for(int i=0;i<len;++i)
{
now=q=ch[now][s[i]-'a'];
while(q>1)ans+=val[q],val[q]=0,q=nxt[q];
}
return ans;
}
}AC;
char s[1000010];
int n,t;
int main()
{
scanf("%d",&t);
while(t--)
{
AC.build();
scanf("%d",&n);
while(n--)scanf("%s",&s),AC.insert(s);
AC.bfs();
scanf("%s",&s),printf("%d\n",AC.query(s));
}
return 0;
}