hdu2222 简单的AC自动机

利用trie树和KMP算法:就是在 Trie 上进行 KMP 匹配。

题意:给你n个单词和一条字符串,问你在这个字符串中,包含几个单词。

思路:这是一条多串匹配的题目,AC自动机

//
#include<iostream>
#include<string.h>
#include<queue>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node
{
    int count;//判断是不是单词的最后一个节点
    struct node *fail;//失败指针
    struct node *next[26];//Tire每个节点的儿子节点
    node()
    {
        fail=NULL;
        count=0;
        memset(next,NULL,sizeof(next));
    }
};
char keyword[10010];
char str[1000010];
void buildTree(char *word,struct node *root)
{
    struct node *p=root;
    int i=0,index;
    int len=strlen(word);
    for(int i=0; i<len; i++)
    {
        index=word[i]-'a';
        if(p->next[index]==NULL)
            p->next[index]=new node();
        p=p->next[index];
    }
    p->count++;
}
void BFS(struct node* root)
{
    queue<struct node*> q;
    struct node *temp,*p;
    root->fail=NULL;
    q.push(root);
    while(!q.empty())
    {
        temp=q.front();
        q.pop();
        for(int 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.push(temp->next[i]);
            }
        }
    }
}
int find(struct node *root)
{
    int cnt=0,index,len=strlen(str);
    struct node *p=root;
    for(int i=0;i<len;i++)
    {
        index=str[i]-'a';
        while(p->next[index]==NULL&&p!=root)//最长后缀
            p=p->fail;
        p=(p->next[index]==NULL?root : p->next[index]);
        struct node *temp=p;
        while(temp!=root&&temp->count!=-1)
        {

            cnt+=temp->count;
            temp->count=-1;
            temp=temp->fail;
        }
    }
    return cnt;
}
int main()
{
    int T;
    int test;
    struct node *root=NULL;
    scanf("%d",&T);
    while(T--)
    {
        root=new node();
        scanf("%d",&test);
        for(int i=0; i<test; i++)
        {
            scanf("%s",keyword);
            buildTree(keyword,root);
        }
        BFS(root);
        scanf("%s",str);
        int ans=find(root);
        printf("%d\n",ans);
    }
    return 0;
}
/*
1
5
she
he
say
shr
her
her
*/


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值