您的位置:首页 > 其它

hdu 2222

2014-07-30 12:16 183 查看
#include<stdio.h>
#include<string.h>
#define N 500000
struct  node
{
node *fail;
node *next[26];
int count;
node()
{
count=0;
memset(next,0,sizeof(next));
fail=NULL;
}
}*q
;
node *root;
int head,tail;
char str[N*2+10];
void insert(char *str)
{
int i,n;
node *p=root;
for(i=0;str[i]!='\0';i++)
{
n=str[i]-'a';
if(p->next
==NULL)
p->next
=new node();
p=p->next
;
}
p->count++;
}
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<26;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,cnt=0;
node *p=root;
while(str[i])
{
int len=str[i]-'a';
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&&temp->count!=-1)
{
cnt+=temp->count;
temp->count=-1;
temp=temp->fail;
}
i++;
}
return cnt;
}
int main()
{
int t,n,i;
char s[100];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
root=new node();
for(i=1;i<=n;i++)
{
scanf("%s",s);
insert(s);
}
head=tail=0;
build_ac_automation();
scanf("%s",str);
printf("%d\n",query(str));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: