3 aaa bbb ccc 2 aaabbbccc bbaacc
web 1: 1 2 3 total: 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
char str[1000010],key[520];
int head,tail;
int an[5050],num,vis[5050];
struct node
{
node *fail;
node *next[130];
int cnt,id;
node()
{
fail=NULL;
cnt=0;
// id=0;
for(int i=0;i<130;i++)
next[i]=NULL;
}
}*q[5000010];
node *root;
void insert(char *s,int id)
{
int temp,len,i;
node *p=root;
len=strlen(s);
for(i=0;i<len;i++)
{
temp=s[i]-31;//都是可见的字符,,不是小写字母
if(p->next[temp]==NULL)
p->next[temp]=new node();
p=p->next[temp];
}
p->cnt=id;
//p->id=id;
}
void build_ac()
{
root->fail=NULL;
q[tail++]=root;
while(head!=tail)
{
node *p=q[head++];
node *temp=NULL;
for(int i=0;i<130;i++)
{
if(p->next[i]!=NULL)
{
if(p==root)
{
p->next[i]->fail=root;
}
else
{
temp=p->fail;
while(temp!=NULL)
{
if(temp->next[i]!=NULL)
{
p->next[i]->fail=temp->next[i];
break;
}
temp=temp->fail;
}
if(temp==NULL)
{
p->next[i]->fail=root;
}
}
q[tail++]=p->next[i];
}
}
}
}
int query()
{
int ans=0,cnt=0;
int len=strlen(str);
node *p=root,*temp;
for(int i=0;i<len;i++)
{
int x=str[i]-31;
while(p->next[x]==NULL&&p!=root)
{
p=p->fail;
}
p=p->next[x];
if(p==NULL)
{
p=root;
}
temp=p;
while(temp!=root&&temp->cnt!=0)
{
//ans+=temp->cnt;
if(temp->cnt&&!vis[temp->cnt])
{
an[num++]=temp->cnt;
vis[temp->cnt]=1;
}
/*if(temp->cnt&&!vis[temp->cnt])
vis[temp->cnt]=1;*/
temp=temp->fail;
cnt++;
}
}
//return ans;
return cnt;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
head=tail=0;
root=new node();
for(i=1;i<=n;i++)
{
scanf("%s",key);
insert(key,i);
}
int m,j,kk;
j=0;
scanf("%d",&m);
build_ac();
for(i=1;i<=m;i++)
{
num=0;
memset(vis,0,sizeof(vis));
scanf("%s",str);
int ans=query();
if(ans)
{
j++;
printf("web %d:",i);
qsort(an,num,sizeof(an[0]),cmp);
// printf("%d\n",num);
for(kk=0;kk<num;kk++)
{
printf(" %d",an[kk]);
}
/*for(kk=1;kk<=n;kk++)
{
if(vis[kk])
printf(" %d",kk);
}*/
printf("\n");
}
}
printf("total: %d\n",j);
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/yu_ch_sh/article/details/47338917