hdu 2222: Keywords Search(AC自动机模板题)

本文详细介绍了使用AC自动机解决字符串匹配问题的具体实现方法。包括AC自动机的结构定义、初始化、插入模式串、构建失败指针及查询过程。通过实际代码展示了如何统计一段文本中特定模式串出现的次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

统计一段字符串中有多少个模板串在里面出现过

#include<bits/stdc++.h>
using namespace std;

const int N=500007;

struct Trie
{
    int next[N][26];
    int fail[N];// fail[i]表示i结点// 
    int end[N];    // end[i]表示以i结点为结尾的模式串个数 
    int L,root;    
    int newnode()
    {
        for(int i=0;i<26;i++)
            next[L][i]=-1;
        end[L++]=0;
        return L-1;
    }
    void init()
    {
        L=0;
        root=newnode();
    }
    void insert(char buf[])
    {
        int now=root;
        for(int i=0;buf[i];i++)
        {
            int ch=buf[i]-'a';
            if(next[now][ch]==-1)
                next[now][ch]=newnode();
            now=next[now][ch];
        }
        end[now]++;
    }
    void build()
    {
        queue<int> Q;
        fail[root]=root;
        for(int i=0;i<26;i++)
        {
            if(next[root][i]==-1)
                next[root][i]=root;
            else
            {
                fail[next[root][i]]=root;
                Q.push(next[root][i]);
            }
        }
        while(!Q.empty())
        {
            int now=Q.front();
            Q.pop();
            for(int i=0;i<26;i++)
            {
                if(next[now][i]==-1)
                    next[now][i]=next[fail[now]][i];//
                else
                {
                    fail[next[now][i]]=next[fail[now]][i];//
                    Q.push(next[now][i]);
                }
            }
        }
    }
    int query(char buf[])
    {
        int now=root;
        int temp,ret=0;
        for(int i=0;buf[i];i++)
        {
            int ch=buf[i]-'a';
            now=next[now][ch];
            temp=now;
            while(temp!=root)
            {
                ret+=end[temp];
                end[temp]=0;    //不作重复计数 
                temp=fail[temp];
            }
        }
        return ret;
    }
}ac;

char buf[1000007];
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        char str[57];
        int n;
        ac.init();
        scanf("%d",&n);
        for(int i=0;i<n;i++)
            scanf("%s",str),ac.insert(str);
        ac.build();
        scanf("%s",buf);
        printf("%d\n",ac.query(buf));
    }
}
View Code

 

转载于:https://www.cnblogs.com/Just--Do--It/p/6479315.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值