hdu 2222(AC自动机 裸题)

来源:互联网 发布:金山软件king计划 编辑:程序博客网 时间:2024/05/18 02:21
#include<iostream>#include<cstring>#include<cstdio>#include<cmath>#include<algorithm>#include<cstdlib>#include<map>#include<queue>#include <deque>#include <list>#include <ctime>#include <stack>#include <vector>#include<iomanip>#include<set>#define Maxn 500010#define modtypedef long long ll;#define FOR(i,j,n) for(int i=j;i<=n;i++)#define DFR(i,j,k) for(int i=j;i>=k;--i)#define lowbit(a) a&-a#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1#define mem(a) memset(a,0,sizeof(a))#define eps 1e-9const int inf = 0x3f3f3f3f;const double pi = acos(-1.0);using namespace std;char str[1000010],keyword[51];int head,tail;struct node {    node * fail;    node * next[26];    int counter;    node()    {   fail=NULL;        counter=0;        FOR(i,0,25)next[i]=NULL;    }}*q[Maxn];node *root;void Insert(char *str){   int temp,len;    node *p=root;    len=strlen(str);    FOR(i,0,len-1)    {   temp=str[i]-'a';        if(p->next[temp]==NULL)p->next[temp]=new node();        p=p->next[temp];    }    p->counter++;}void buildAC(){   q[tail++]=root;    while(head!=tail)    {   node *p=q[head++];        node *temp=NULL;        FOR(i,0,25)        {   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 index,len,result;    node *p=root;    result=0;    len=strlen(str);    FOR(i,0,len-1)    {   index=str[i]-'a';        while(p->next[index]==NULL&&p!=root)            p=p->fail;        p=p->next[index];        if(p==NULL)p=root;        node *temp=p;        while(temp!=root && temp->counter!=-1)        {   result += temp->counter;            temp->counter=-1;            temp=temp->fail;        }    }    return result;}int main(){   int T,num;cin>>T;    FOR(i,1,T)    {head=tail=0;     root =new node();     scanf("%d",&num);     getchar();     FOR(j,1,num)     {gets(keyword);      Insert(keyword);     }   //  buildAC();     buildAC();     scanf("%s",str);     printf("%d\n",query());    }    return 0;}

0 0
原创粉丝点击