AC自动机模板代码

#include <iostream>
#include <queue>
#include <string>
#include <cstring>

using namespace std;

const int MAX_NODES = 1000000;   // 最大节点数,根据需求调整

// ---------- 节点结构体 ----------
struct Node {
    int next[26];       // 子节点编号,0 表示空
    int fail;           // 失配指针
    bool is_end;        // 是否为单词结尾
    string word;        // 结尾单词(非结尾为空)

    Node() {
        memset(next, 0, sizeof(next));
        fail = 0;
        is_end = false;
        word = "";
    }
};

// ---------- 全局数组 ----------
Node nodes[MAX_NODES];
int node_cnt;           // 当前使用的节点数(根节点为 0)

// ---------- 初始化 ----------
void init() {
    node_cnt = 1;       // 根节点编号 0
    // 重置根节点(可选,因为全局数组已默认构造)
    nodes[0] = Node();
}

// ---------- 插入模式串 ----------
void add_word(const string& word) {
    int p = 0;
    for (char ch : word) {
        int idx = ch - 'a';
        if (nodes[p].next[idx] == 0) {
            nodes[p].next[idx] = node_cnt;
            nodes[node_cnt] = Node();   // 初始化新节点
            ++node_cnt;
        }
        p = nodes[p].next[idx];
    }
    nodes[p].is_end = true;
    nodes[p].word = word;
}

// ---------- 构建失配指针 ----------
void build_fail_pointers() {
    queue<int> q;
    // 根节点的所有子节点 fail 指向根节点
    for (int i = 0; i < 26; ++i) {
        int child = nodes[0].next[i];
        if (child != 0) {
            nodes[child].fail = 0;
            q.push(child);
        }
    }

    while (!q.empty()) {
        int cur = q.front();
        q.pop();

        for (int i = 0; i < 26; ++i) {
            int child = nodes[cur].next[i];
            if (child != 0) {
                // 计算 child 的 fail 指针
                int f = nodes[cur].fail;
                while (f != 0 && nodes[f].next[i] == 0) {
                    f = nodes[f].fail;
                }
                if (nodes[f].next[i] != 0) {
                    nodes[child].fail = nodes[f].next[i];
                } else {
                    nodes[child].fail = 0;
                }
                q.push(child);
            }
        }
    }
}

// ---------- 搜索 ----------
vector<string> search(const string& text) {
    vector<string> result;
    int p = 0;

    for (char ch : text) {
        int idx = ch - 'a';
        while (p != 0 && nodes[p].next[idx] == 0) {
            p = nodes[p].fail;
        }
        if (nodes[p].next[idx] != 0) {
            p = nodes[p].next[idx];
        }

        int temp = p;
        while (temp != 0) {
            if (nodes[temp].is_end) {
                result.push_back(nodes[temp].word);
            }
            temp = nodes[temp].fail;
        }
    }
    return result;
}

// ---------- 使用示例 ----------
int main() {
    init();
    add_word("he");
    add_word("she");
    add_word("his");
    add_word("hers");
    build_fail_pointers();

    string text = "ushers";
    vector<string> matches = search(text);
    for (const string& w : matches) {
        cout << w << " ";
    }
    cout << endl;   // 输出: she he hers
    return 0;
}

1 条评论

  • 1