hdu 2222(AC自动机 裸题)

#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 mod
typedef 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-9
const 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值