HDU 2222(ac自动机)

本文深入探讨了AC自动机的原理与应用,通过详细解释其数据结构和算法流程,包括插入单词、获取失败指针及查询过程。文章提供了一个完整的C++实现代码示例,展示了如何构建AC自动机来高效地进行字符串匹配。

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

ac自动机

参考博客:https://blog.youkuaiyun.com/bestsort/article/details/82947639

#include<queue>
#include<cstdlib>
#include<cmath>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#define debug(x) cout<<#x<<" = "<<x<<endl
#define gg cout<<"-----QAQ-----"<<endl
using namespace std;
typedef long long ll;
const int maxn = 500010;

int trie[maxn][26];
int cntword[maxn];
int fail[maxn];
int cnt = 0;

void insertWords(string s)
{
    int root = 0;
    for(int i = 0; i <s.size(); ++i) {
        int next = s[i]-'a';
        if(!trie[root][next])
            trie[root][next] = ++cnt;
        root = trie[root][next];
    }
    cntword[root]++;
}
void getFail()
{
    queue<int> q;
    for(int i = 0; i < 26; ++i) {
        if(trie[0][i]) {
            fail[trie[0][i]] = 0;
            q.push(trie[0][i]);
        }
    }


    while(!q.empty()){
        int now = q.front();q.pop();
        for(int i = 0; i < 26; ++i)  {
            if(trie[now][i]) {
                fail[trie[now][i]] = trie[fail[now]][i];
                q.push(trie[now][i]);
            }
            else trie[now][i] = trie[fail[now]][i];
        }
    }
}

int query(string s)
{
    int now = 0, ans = 0;
    for(int i = 0; i < s.size(); ++i) {
        now = trie[now][s[i]-'a'];
        for(int j = now; j&&cntword[j]!=-1;j=fail[j]) {
            ans += cntword[j];
            cntword[j] = -1;
        }
    }
    return ans;
}
void init()
{
    cnt = 0;
    for(int i = 0; i < 26; ++i) {
        for(int j = 0; j < maxn; ++j)
            trie[j][i] = 0;
    }
    memset(fail, 0, sizeof(fail));
    memset(cntword, 0, sizeof(cntword));
}
void solve()
{
    init();
    int n;string s;
    cin >> n;
    for(int i = 1; i <= n; ++i) {
        cin >> s;
        insertWords(s);
    }
    getFail();
    cin >> s;
    cout<<query(s)<<endl;

}
int main()
{
    int t;
    cin >> t;
    while(t--)
        solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值