HDU 1277 全文检索【AC自动机】
#include<stdio.h>优质内容筛选与推荐>>
#include<string.h>
char str[55],s[10000000];
int front,rear,K;
int f[60000];
struct node
{
node *fail;
node *next[10];
int count;
node ()
{
fail=NULL;
count=0;
memset(next,0,sizeof(next));
}
}*q[500001];
void add(char *a,node *root,int num)
{
int i=0,x;
node *p=root;
while(a[i])
{
x=a[i]-'0';
if(p->next[x]==NULL)
p->next[x]=new node();
p=p->next[x];
i++;
}
p->count=num;
}
void build_ac(node *root)
{
int i;
front=rear=0;
root->fail=NULL;
q[rear++]=root;
while(front<rear)
{
node *x=q[front++];
node *p=NULL;
for(i=0;i<10;i++)
if(x->next[i]!=NULL)
{
if(x==root)
x->next[i]->fail=root;
else
{
p=x->fail;
while(p!=NULL)
{
if(p->next[i]!=NULL)
{
x->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL)
x->next[i]->fail=root;
}
q[rear++]=x->next[i];
}
}
}
void ac(node *root)
{
K=0;
int i=0,tot=0,x,len=strlen(s);
node *p=root;
while(s[i])
{
x=s[i]-'0';
while(p->next[x]==NULL&&p!=root)
p=p->fail;
p=p->next[x];
p=(p==NULL)?root:p;
node *tmp=p;
while(tmp!=root&&tmp->count!=-1)
{
if(tmp->count)
f[K++]=tmp->count;
tmp->count=-1;
tmp=tmp->fail;
}
i++;
}
}
int main()
{
int i,n;
char ch=0;
while(scanf("%*d%d",&n)!=EOF)
{
node *root;
root=new node();
for(i=0;;){
s[i]=getchar();
if(s[i]==10)
{
if(ch==10)break;
ch=10;continue;
}
ch=s[i++];
}
s[i]='\0';
for(i=1;i<=n;i++)
{
scanf("%*s%*s%*s%s",str);
add(str,root,i);
}
build_ac(root);
ac(root);
if(K)
{
printf("Found key:");
for(i=0;i<K;i++)printf(" [Key No. %d]",f[i]);
printf("\n");
}
else printf("No key can be found !");
}
return 0;
}