HDU 5384 (AC自动机)

本文介绍了一种使用AC自动机进行批量模式串匹配的方法。通过构建AC自动机,可以高效地找出一组模式串在一个或多个文本串中的出现次数。文章提供了完整的C++实现代码,并详细解释了AC自动机的构建过程及查询算法。

题目链接:点击这里

题意:给出n个文本串和m个模式串,求每一个文本串中出现的模式串次数总和。

给m个模式串建AC自动机,然后每一个文本串询问一次就好了。

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <queue>
using namespace std;
#define maxn 111111
#define maxm 1111111

int n, m;
string a[maxn];
char str[maxn];
struct trie {
    int next[maxn][26], fail[maxn], end[maxn];
    int root, cnt;
    int new_node () {
        memset (next[cnt], -1, sizeof next[cnt]);
        end[cnt++] = 0;
        return cnt-1;
    }
    void init () {
        cnt = 0;
        root = new_node ();
    }
    void insert (char *buf) {//字典树插入一个单词
        int len = strlen (buf);
        int now = root;
        for (int i = 0; i < len; i++) {
            int id = buf[i]-'a';
            if (next[now][id] == -1) {
                next[now][id] = new_node ();
            }
            now = next[now][id];
        }
        end[now]++;
    }
    void build () {//构建fail指针
        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 (string buf) {
        int len = buf.length ();
        int now = root;
        int res = 0;
        for (int i = 0; i < len; i++) {
            int id = buf[i]-'a';
            now = next[now][id];
            int tmp = now;
            while (tmp != root) {
                res += end[tmp];
                tmp = fail[tmp];//沿着失配边走
            }
        }
        return res;
    }
}ac;

int main () {
    int t;
    scanf ("%d", &t);
    while (t--) {
        scanf ("%d%d", &n, &m);
        ac.init ();
        for (int i = 1; i <= n; i++) {
            scanf ("%s", str);
            a[i] = (string) str; 
        }
        for (int i = 1; i <= m; i++) {
            scanf ("%s", str);
            ac.insert (str);
        }
        ac.build ();
        for (int i = 1; i <= n; i++) { 
            printf ("%d\n", ac.query (a[i]));
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值