题意:
中文题。
题解:
AC模板题,这道模板题在里面加个数组ans表示病毒的数量就可以了。
题外话:
这道题让我发现了我还是未能很好的理解AC自动机里的fail指针的指向,起初我看到会出现重叠的,我就想着像KMP重叠那样做,匹配到了就指向该节点的失配指针所指向的地方,然后就不断的指向自身,导致爆炸了。。这句话说的有点不对,怎么说呢,我找了挺多的博客的,感觉这位大佬说的话让我感觉瞬间清楚了,AC自动机自身就有着类似于重置机制的功能。
沐阳:其实该题没有想象中的那么复杂,仔细一想就知道,AC自动机自身不是有一个重置操作吗,即找的的子串曾经被我们删除过,该题只要不进行删除操作就行了,这都多亏了在该算法中,本身的fail指针是不停的回溯的,例如AAA匹配AA时,前面的AA计算一次,到达第三个A时,由于后面的AA只有两个字符,算法将自动跳到AA的第二个A来匹配AAA中的第三个A,就是这样。
他的博客:
https://www.cnblogs.com/Lyush/archive/2011/09/07/2169478.html
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXN=2000000+7;
struct node
{
int sum;
int number;
node *fail;
node *next[128];
node(){
fail=0;
sum=0;
number=0;
for(int i=0;i<128;i++)
next[i]=0;
}
}*root;
char c[1007][57];
char str[MAXN];
int tot;
int ans[1007];
void insert(char *s)
{
node *r=root;
for(int i=0;s[i];i++)
{
int x=s[i];
if(r->next[x]==0) r->next[x]=new(node);
r=r->next[x];
}
r->number=tot++;
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<128;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)
{
node *p=root;
int len=strlen(s);
for(int i=0;i<len;i++)
{
int x=s[i];
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)
{
ans[temp->number]++;
}
temp=temp->fail;
}
}
}
void del(node *head)
{
for(int i=0;i<128;i++)
if(head->next[i])
del(head->next[i]);
delete(head);
}
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(ans,0,sizeof(ans));
root=new(node);
tot=1;
for(int i=1;i<=n;i++)
{
scanf("%s",c[i]);
insert(c[i]);
}
getfail();
scanf("%s",str);
ac_automation(str);
for(int i=1;i<=n;i++)
if(ans[i])
printf("%s: %d\n",c[i],ans[i]);
del(root);
}
}