hdu 2222

来源:互联网 发布:大苗医考网官网网络班 编辑:程序博客网 时间:2024/04/29 05:04
#include<stdio.h>#include<string.h>#define N 500000struct  node{    node *fail;    node *next[26];    int count;    node()    {        count=0;        memset(next,0,sizeof(next));        fail=NULL;    }}*q[N]; 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[n]==NULL)          p->next[n]=new node();        p=p->next[n];    }    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;}

0 0
原创粉丝点击