题解:
AC自动机模板题,下面是我学习的两个博客:
http://blog.csdn.net/creatorx/article/details/71100840
http://blog.csdn.net/niushuai666/article/details/7002823#reply
在学习AC自动机之前最好先学习一下字典树和KMP,前者用来搭建AC自动机的体系,后者用到它的思想,另外AC自动机的时间复杂度为O(n+m),n为文本串的总长度,m为匹配串的总长度。
看博客的时候最好模拟一下,你会发现有奇效。
下面是我的模板,等会去学一下优化。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXN=1000000+7;
struct node
{
int sum;
node *fail;
node *next[26];
node(){
sum=0;
fail=0;
for(int i=0;i<26;i++)
next[i]=0;
}
}*root;
char str[MAXN];
int cnt;
void insert(char *s)
{
node *r=root;
for(int i=0;s[i];i++)
{
int x=s[i]-'a';
if(r->next[x]==0) r->next[x]=new(node);
r=r->next[x];
}
r->sum++;
}
void getfail()
{
queue<node *>q;
q.push(root);
node *p;
node *temp;
while(!q.empty())
{
temp=q.front();
q.pop();
for(int i=0;i<26;i++)
{
if(temp->next[i])
{
if(temp==root)
{
temp->next[i]->fail=root;
}
else
{
p=temp->fail;
while(p)
{
if(p->next[i])
{
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==0)
temp->next[i]->fail=root;
}
q.push(temp->next[i]);
}
}
}
}
void ac_automation(char *s)
{
getfail();
node *p=root;
int len=strlen(s);
for(int i=0;i<len;i++)
{
int x=s[i]-'a';
while(!p->next[x]&&p!=root) p=p->fail;
p=p->next[x];
if(!p) p=root;
node *temp=p;
while(temp!=root)
{
if(temp->sum>=0)
{
cnt+=temp->sum;
temp->sum=-1;
}
// else//这个else最好不要加上去,因为我做了一些题,发现这个else会WA,去掉这个就过了。
// break;
temp=temp->fail;
}
}
}
void del(node *head)
{
for(int i=0;i<26;i++)
if(head->next[i])
del(head->next[i]);
delete(head);
}
int main()
{
int t,n;
char c[57];
scanf("%d",&t);
while(t--)
{
root=new(node);
cnt=0;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%s",c);
insert(c);
}
scanf("%s",str);
ac_automation(str);
printf("%d\n",cnt);
del(root);
}
}