第一道ac自动机题,ac自动机算法的理解(crazyacking的博客http://www.cnblogs.com/crazyacking/p/4002807.html +ppt(http://wenku.baidu.com/view/93af2c936bec0975f465e2f1.html))
#include<bits/stdc++.h>
using namespace std;
char str[1000100];
struct node
{
int cnt;
node *next[26],*fail;
void init()
{
for(int i=0;i<26;i++)
next[i]=NULL;
cnt=0;
fail=NULL;
}
}*root;
void mt()
{
node *p=root;
int len=strlen(str);
for(int i=0;i<len;i++)
{
int pos=str[i]-'a';
if(p->next[pos]==NULL)
{
p->next[pos]=new node;
p->next[pos]->init();
p=p->next[pos];
}
else
p=p->next[pos];
}
p->cnt++;
}
void mf()
{
node *son,*temp,*p=root;
queue<node *>qu;
qu.push(p);
while(!qu.empty())
{
temp=qu.front();
qu.pop();
for(int i=0;i<26;i++)
{
son=temp->next[i];
if(son)
{
if(temp==root)
son->fail=root;
else
{
p=temp->fail;
while(p)
{
if(p->next[i])
{
son->fail=p->next[i];
break;
}
p=p->fail;
}
if(!p)
son->fail=root;
}
qu.push(son);
}
}
}
}
void sm()
{
int len=strlen(str);
node *p=root,*temp;
int ans=0;
for(int i=0;i<len;i++)
{
int pos=str[i]-'a';
while(!p->next[pos]&&p!=root)
p=p->fail;
p=p->next[pos];
if(!p)
p=root;
temp=p;
while(temp!=root)
{
if(temp->cnt>=0)
{
ans+=temp->cnt;
temp->cnt=-1;
}
else
break;
temp=temp->fail;
}
}
printf("%d\n",ans);
}
int main()
{
int T,n;
scanf("%d",&T);
while(T--)
{
root=new node;
root->init();
scanf("%d",&n);
getchar();
for(int i=0;i<n;i++)
{
gets(str);
mt();
}
mf();
gets(str);
sm();
}
return 0;
}