題意:
中文題。
題解:
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);
}
}