AC自动机——会自我纠错的查词器

· · 算法·理论

AC自动机——会自我纠错的查词器

概述:用字典树和失败指针,一次性找到所有可能的单词,就像在错别字文章中自动发现正确单词。

想象你在读一篇有很多错别字的文章,你想同时查出“苹果”、“香蕉”、“西瓜”这三个词是否出现。如果一个个查,太慢了。AC自动机就像一个聪明的查词器,它先建一本“字典树”,把所有要查的词假装成树根下的分支。然后它给每个节点设置一个“失败指针”——当你走到某个字母发现走不通时,失败指针会把你弹到别的分支上,继续尝试匹配。这样你只需要读一遍文章,就能知道所有词是否出现。

下面是一个简单的C++例子(只展示核心思路)。它先插入单词,然后构建失败指针,最后在文本中同时查找所有单词。

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

const int MAXN = 100000;       // 足够大
int trie[MAXN][26], fail[MAXN], cnt[MAXN], tot;

void insert(const string &s) {
    int u = 0;
    for (char c : s) {
        int v = c - 'a';
        if (!trie[u][v]) trie[u][v] = ++tot;
        u = trie[u][v];
    }
    cnt[u]++;                 // 这个单词末尾标记
}

void build() {                // BFS建立失败指针
    queue<int> q;
    for (int i = 0; i < 26; i++)
        if (trie[0][i]) q.push(trie[0][i]);
    while (!q.empty()) {
        int u = q.front(); q.pop();
        for (int i = 0; i < 26; i++) {
            int v = trie[u][i];
            if (v) {
                fail[v] = trie[fail[u]][i];   // 核心:失配跳转
                q.push(v);
            } else {
                trie[u][i] = trie[fail[u]][i]; // 路径压缩(可选)
            }
        }
    }
}

int query(const string &text) {
    int u = 0, res = 0;
    for (char c : text) {
        u = trie[u][c - 'a'];
        for (int v = u; v && cnt[v] != -1; v = fail[v]) {
            res += cnt[v];
            cnt[v] = -1;     // 避免重复计数
        }
    }
    return res;
}

用几个单词建好AC自动机后,调用 query("文本") 就能得到一共命中了几次。简单吧?这个“纠错器”在搜索引擎、病毒扫描中都会用到。

例题精讲

1.单选题

在AC自动机中,当当前节点u没有字符c的转移时,匹配过程应如何继续?

::::info[查看答案] 正确答案:B ::::

2.判断题 AC自动机是一种结合了Trie树和KMP算法思想的字符串多模式匹配数据结构。 ::::info[查看答案] 正确答案:正确 ::::

3.填空题 以下代码实现AC自动机的构建过程(使用Trie图优化)。请补全缺失的部分。

void build() {
    queue<int> q;
    for (int i = 0; i < 26; i++) {
        if (trie[0][i]) {
            fail[trie[0][i]] = 0;
            q.push(trie[0][i]);
        } else {
            trie[0][i] = 0;
        }
    }
    while (!q.empty()) {
        int u = q.front(); q.pop();
        for (int i = 0; i < 26; i++) {
            int v = trie[u][i];
            if (v) {
                fail[v] = ___;
                q.push(v);
            } else {
                trie[u][i] = trie[fail[u]][i];
            }
        }
    }
}

正确答案: ::::info[查看答案] 正确答案:trie[fail[u]][i] ::::