HDU2222 Keywords Search AC自动机

/*
题目大意:给你n个关键字和一个模式串,让你找出模式串中有多少个关键字

分析:AC自动机入门题。可以作为AC自动机的模板
*/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
#define son_num 26
#define maxn 1000005
char str0[maxn];
struct node
{
    node *fail;
    node *next[son_num];
    int num; //纪录当前节点对应单词重复的个数
    node()
    {
        fail=NULL;
        num=0;
        memset(next,NULL,sizeof(next));
    }
};
//构造Tire树
void insert(node *root,char *str)
{
    node *p=root;
    int i=0,index;
    while(str[i])
    {
        index=str[i]-'a';
        if(p->next[index]==NULL)
          p->next[index]=new node();
        p=p->next[index];
        i++;
    }
    p->num++;
}
//寻找失败指针
void build_fail(node *root)
{
    queue <node *> que;
    root->fail=NULL;
    que.push(root);
    while(!que.empty())
    {
        node *temp=que.front(); //取队首元素
        que.pop();
        node *p=NULL;
        for(int i=0;i<son_num;i++)
        {
            if(temp->next[i]!=NULL) //寻找当前子树的失败指针
            {
                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;
                que.push(temp->next[i]);
            }
        }
    }
}
//询问str中包含多少个关键字
int query(node *root,char *str)
{
    int i=0,cnt=0,index,len;
    len=strlen(str);
    node *p=root;
    while(str[i])
    {
        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->num!=-1)
        {
            //if(temp->num!=0)
            cnt+=temp->num;
            temp->num=-1;
            temp=temp->fail;
        }
        i++;
    }
    return cnt;
}
int main()
{
    int t,n;
    char str[55];
    cin>>t;
    while(t--)
    {
        scanf("%d",&n);
        node *root=new node();
        for(int i=0;i<n;i++)
        {
            scanf("%s",str);
            insert(root,str);
        }
        build_fail(root);
        scanf("%s",str0);
        printf("%d\n",query(root,str0));
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值