#include<stdio.h>
#include<string.h>
int cnt[1005];
char str[1005][100],s[2000005];
struct node
{
node *fail;
node *next[33];
int id;
node()
{
id=0;
fail=NULL;
memset(next,0,sizeof(next));
}
}*q[50005];
node *root;
void insert(char *str,int id)
{
int i;
node *p=root;
for(i=0; str[i]!='\0'; i++)
{
int len=str[i]-'A';
if(p->next[len]==NULL)
p->next[len]=new node();
p=p->next[len];
}
p->id=id;
}
void build_ac_automation()
{
int head=0,tail=0,i;
q[head++]=root;
root->fail=NULL;
while(head!=tail)
{
node *temp=q[tail++];
node *p=NULL;
for(i=0; i<32; i++)
{
if(temp->next[i]!=0)
{
if(temp==root)
temp->next[i]->fail=root;
else
{
p=temp->fail;
while(p!=NULL)
{
if(p->next[i]!=NULL)
{
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL)
temp->next[i]->fail=root;
}
q[head++]=temp->next[i];
}
}
}
}
void query(char *str)
{
int i=0,n;
node *p=root;
while(str[i])
{
if(str[i]>='A'&&str[i]<='Z')
{
n=str[i]-'A';
while(p->next[n]==NULL&&p!=root)
p=p->fail;
p=p->next[n];
p=(p==NULL)?root:p;
node *temp=p;
while(temp!=root&&temp->id>0)
{
cnt[temp->id]++;
temp=temp->fail;
}
}
else
p=root;
i++;
}
}
int main()
{
int i,n;
while(scanf("%d",&n)!=EOF)
{
root=new node();
for(i=1; i<=n; i++)
{
scanf("%s",str[i]);
insert(str[i],i);
}
build_ac_automation();
memset(cnt,0,sizeof(cnt));
scanf("%s",s);
query(s);
for(i=1; i<=n; i++)
if(cnt[i]!=0)
printf("%s: %d\n",str[i],cnt[i]);
}
}
hdu 3065
最新推荐文章于 2022-06-11 23:47:38 发布
