HDU 2222 Keywords Search

这个题是AC自动机的模版题;

#include<stdio.h>
#include
<stdlib.h>
#include
<string.h>
struct node
{
int flag;
node
*ch[26],*fail;
}
*q[1000024];
node
*empty( )
{
node
*t=( node * )malloc( sizeof( node ) );
memset( t
->ch,NULL,sizeof( t->ch ) );
t
->flag=0 ; t->fail=NULL ;
return t;
}
void build_tire( node *t,char num[] )
{
int i=0;
while( num[i] )
{
int x=num[i]-'a';
if( t->ch[x]==NULL )
t
->ch[x]=empty( );
t
=t->ch[x];
i
++;
}
t
->flag++;
}
void AC_automation( node *root )
{
int first=0,end=0;
q[first
++]=root;
while( first>end )
{
node
*temp = q[end++];
for( int i=0;i<26;i++ )
{
if( temp->ch[i] )
{
if( temp==root )
temp
->ch[i]->fail=root;
else
{
node
*p=temp->fail;
while( p )
{
if( p->ch[i] )
{
temp
->ch[i]->fail=p->ch[i];
break;
}
p
=p->fail;
}
if(p==NULL )
{
temp
->ch[i]->fail=root;
}

}
q[first
++]=temp->ch[i];
}
}
}
}
int research( node *root,char num[] )
{
int i=0,sum=0;
node
*temp=root;
while( num[i] )
{
int x=num[i]-'a';
while( temp->ch[x]==NULL&&temp!=root )
temp
=temp->fail;
temp
=temp->ch[x];
if( temp==NULL )
temp
=root;
node
*p=temp;
while( p!=root&&p->flag!=-1 )
{
sum
+=p->flag;
p
->flag=-1;
p
=p->fail;
}
i
++;
}
return sum;
}
int main()
{
int T,n;
char num[1000024];
scanf(
"%d",&T );
while( T-- )
{
node
*root=empty( );
scanf(
"%d",&n );
for( int i=0;i<n;i++ )
{
scanf(
"%s",num );
build_tire( root,num );
}
scanf(
"%s",num );
AC_automation( root );
printf(
"%d\n",research( root,num ) );
}
}
posted @ 2011-09-18 20:14  wutaoKeen  阅读(180)  评论(0编辑  收藏  举报