【luogu P3808 AC自动机(简单版)】 模板

本文介绍了一种使用AC自动机处理字符串匹配问题的方法。通过构建字典树并预先处理得到失败指针,实现了高效的字符串匹配搜索。文章提供了一个完整的C++实现示例,包括插入字符串到字典树、构建失败指针以及进行模式串匹配等关键步骤。

题目链接:https://www.luogu.org/problemnew/show/P3808

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000010;
int n, trie[maxn][27], next[maxn], tot, vis[maxn];
char s[maxn];
queue<int> q;
void _insert(char s[])
{
    int now = 0;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int x = s[i]-'a';
        if(!trie[now][x])
        trie[now][x] = ++tot;
        now = trie[now][x];
    }
    vis[now]++;
}
void get_next()
{
    for(int i = 0; i < 26; i++)
    {
        if(trie[0][i])
        {
            next[trie[0][i]] = 0;
            q.push(trie[0][i]);
        }
    }
    while(!q.empty())
    {
        int cnt = q.front(); q.pop();
        for(int i = 0; i < 26; i++)
        {
            if(trie[cnt][i])
            {
                next[trie[cnt][i]] = trie[next[cnt]][i];
                q.push(trie[cnt][i]);
            }
            else
            trie[cnt][i] = trie[next[cnt]][i];
        }
    }
}
int find(char s[])
{
    int now = 0, ans = 0;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int x = s[i]-'a';
        now = trie[now][x];
        for(int k = now; k&&~vis[k]; k = next[k])
        {
            ans += vis[k];
            vis[k] = -1;
        }
    }
    return ans;
}
int main()
{
    std::ios::sync_with_stdio(false);
    cin>>n;
    for(int i = 1; i <= n; i++)
    {
        cin>>s;
        _insert(s);
    }
    get_next();
    cin>>s;
    cout<<find(s);
    return 0;
}

转载于:https://www.cnblogs.com/MisakaAzusa/p/9231126.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值