HDU 3065 (AC自动机)

本文介绍了一种使用AC自动机来统计文本中每个单词出现次数的方法。通过构建字典树并利用失配指针优化匹配过程,实现了高效统计。代码详细展示了AC自动机的构建及查询流程。

题目链接:点击这里

题意:需要统计每一个单词在文本中出现的次数

没有重复的单词,直接拿来跑自动机就好.

#include <bits/stdc++.h>
using namespace std;
#define maxn 51111
#define maxm 2111111

int n, m;
char str[1111][55];
char a[maxm];
struct trie {
    int next[maxn][110], fail[maxn], end[maxn];
    int root, cnt;
    int num[maxn];//每个单词出现的次数
    int f[maxn]; //字典树上的节点对应的病毒编号
    int new_node () {
        memset (next[cnt], -1, sizeof next[cnt]);
        end[cnt++] = 0;
        return cnt-1;
    }
    void init () {
        cnt = 0;
        root = new_node ();
        memset (f, -1, sizeof f);
        memset (num, 0, sizeof num);
    }
    void insert (char *buf, int pos) {//字典树插入一个单词
        int len = strlen (buf);
        int now = root;
        for (int i = 0; i < len; i++) {
            int id = buf[i]-20;
            if (next[now][id] == -1) {
                next[now][id] = new_node ();
            }
            now = next[now][id];
        }
        end[now]++;
        f[now] = pos;
    }
    void build () {//构建fail指针
        queue <int> q;
        fail[root] = root;
        for (int i = 0; i < 110; 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 < 110; 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 len = strlen (buf);
        int now = root;
        for (int i = 0; i < len; i++) {
            int id = buf[i]-20;
            now = next[now][id];
            int tmp = now;
            while (tmp != root) {
                if (end[tmp]) {
                    num[f[tmp]] += end[tmp];
                }
                tmp = fail[tmp];//沿着失配边走
            }
        }
        for (int i = 1; i <= n; i++) {
            if (num[i]) {
                printf ("%s: %d\n", str[i], num[i]);
            }
        }
        return 0;
    }
}ac;

int main () {
    //freopen ("in.txt", "r", stdin);
    while (scanf ("%d", &n) == 1) {
        ac.init ();
        for (int i = 1; i <= n; i++) {
            scanf ("%s", str[i]);
            ac.insert (str[i], i);
        }
        ac.build ();
        scanf ("%s", a);
        ac.query (a);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值