#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
bool cmp(int a,int b)
{
return a<b;
}
struct node
{
node *fail;
node *next[95];
int id;
node()
{
id=0;//注意初始化
fail=NULL;
memset(next,0,sizeof(next));
}
}*q[200005];
node *root;
int head,tail,num,a[600],mark[600];
void insert(char *str,int id)
{
int i;
node *p=root;
for(i=0;str[i]!='\0';i++)
{
int len=str[i]-32;
if(p->next[len]==NULL)
p->next[len]=new node();
p=p->next[len];
}
p->id=id;
}
void build_ac_automation()
{
int i;
q[head++]=root;
root->fail=NULL;
while(head!=tail)
{
node *temp=q[tail++];
node *p=NULL;
for(i=0;i<95;i++)
{
if(temp->next[i]!=NULL)
{
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];
}
}
}
}
int query(char *str)
{
int i=0;
node *p=root;
memset(mark,0,sizeof(mark));
while(str[i])
{
int len=str[i]-32;
while(p->next[len]==NULL&&p!=root)
p=p->fail;
p=p->next[len];
p=(p==NULL)?root:p;
node *temp=p;
while(temp!=root&&!mark[temp->id])
{
if(temp->id!=0)
a[num++]=temp->id;
mark[temp->id]=1;
temp=temp->fail;
}
i++;
}
return num;
}
int main()
{
int n,m,sum,i,ans,j;
char str[20005];
while(scanf("%d",&n)!=EOF)
{
root=new node();
for(i=1;i<=n;i++)
{
scanf("%s",str);
insert(str,i);
}
head=tail=0;
build_ac_automation();
scanf("%d",&m);
sum=0;
for(i=1;i<=m;i++)
{
scanf("%s",str);
num=0;
ans=query(str);
if(ans!=0)
{
sum++;
sort(a,a+num,cmp);
printf("web %d:",i);
for(j=0;j<ans;j++)
printf(" %d",a[j]);
printf("\n");
}
}
printf("total: %d\n",sum);
}
return 0;
}
hdu 2896
最新推荐文章于 2020-10-08 10:49:21 发布