记录ac自动机模板

const int maxn = 4e5 + 5;

char s[maxn];

struct AC_Automaton {
    int next[maxn][26];
    int fail[maxn];
    int sz, root;

    int newNode() {
        memset(next[sz], 0, sizeof(next[sz]));
        fail[sz] = 0;
        return sz++;
    }

    void init() {
        sz = 0;
        root = newNode();
    }

    int add() {
        int p = root;
        for (int i = 0, c; s[i]; ++i) {
            c = s[i] - 'a';
            if (!next[p][c]) {
                next[p][c] = newNode();
            }
            p = next[p][c];
        }
        return p;
    }

    void getFail() {
        queue<int> q;
        for (int i = 0; i < 26; i++) {
            if (next[root][i]) {
                q.push(next[root][i]);
            } else {
                next[root][i] = root;
            }
        }
        while (!q.empty()) {
            int p = q.front();
            q.pop();

            for (int i = 0; i < 26; i++) {
                if (next[p][i]) {
                    fail[next[p][i]] = next[fail[p]][i];
                    q.push(next[p][i]);
                } else {
                    next[p][i] = next[fail[p]][i];
                }
            }
        }
    }

} ac;

你可能感兴趣的:(ACM,AC自动机,模板集合)