shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: Aho-Corasick
(src/string/aho-corasick.hpp)

複数のパターンを、文字列の中から一度に探す AhoCorasick<K, Base> です。パターンを add で追加してから build を呼びます。文字 c は c - Base として $0$ 以上 $K$ 未満の番号に直します。

AhoCorasick<26, 'a'> ac;
ac.add("he");                 // パターン 0
ac.add("she");                // パターン 1
ac.add("hers");               // パターン 2
ac.build();
ac.count("ushers");           // 3 ("she"、"he"、"hers")
ac.count_each("ushers");      // {1, 1, 1}
for (auto [pos, id] : ac.find_all(std::string("ushers"))) {
    // (1, 1), (2, 0), (2, 2) の順
}

// オートマトンの上の DP: ノードを状態にして、文字を読むたびに next で移る
long long v = 0;
for (char c : text) {
    v = ac.next(v, c);
    if (ac.match_count(v) > 0) { /* ここで終わるパターンがある */ }
}

ノードは Trie と同じく、文字列を追加した順に作った番号を持ちます。根はノード 0 (空文字列) です。パターンは空でない文字列に限ります。同じパターンを何度も追加でき、別のパターンとして数えます。

ノードの番号・個数などは long long です。ノードの中身は int で持つので、メモリはノード 1 つあたり $4K + 24$ バイトです。

$L$ をパターンの長さの合計 (ノード数は $L + 1$ 以下)、$P$ をパターンの個数、$\lvert t \rvert$ を探す文字列の長さとします。

メンバ関数

関数 説明 計算量
AhoCorasick<K, Base>() 空の状態 (根だけ)。既定は K = 26、Base = 'a' $O(K)$
add(s) パターン s を追加し、パターンの番号 (追加した順に 0, 1, …) を返す。build の前に呼ぶ $O(\lvert s \rvert K)$
build() 失敗リンクと遷移を作る。パターンを追加し終えてから 1 回だけ呼ぶ $O(LK)$
count(t) t に現れるパターンの個数の合計 (同じパターンの出現もすべて数える) $O(\lvert t \rvert)$
count_each(t) パターンごとの、t に現れる回数の std::vector<long long> $O(\lvert t \rvert + L + P)$
find_all(t) t に現れるパターンを Match {pos, id} (開始位置, パターンの番号) として遅延列挙する range を返す。終わる位置の順に並び、同じ位置で終わるものは長いパターンから、同じパターンは番号の小さい順に並ぶ 構築 $O(1)$、全走査 $O(\lvert t \rvert + \text{出力の個数})$
next(v, c) ノード v で文字 c を読んだときに移るノード $O(1)$
match_count(v) ノード v の文字列の接尾辞になっているパターンの個数 (v に着いたときに終わるパターンの個数) $O(1)$
link(v) 失敗リンク (v の文字列の最長の真の接尾辞のうち、ノードのあるもの)。根なら -1 $O(1)$
node(i) パターン i が終わるノード $O(1)$
parent(v) ノード v の親 (根なら -1) $O(1)$
depth(v) ノード v の深さ (対応する文字列の長さ) $O(1)$
size() ノードの個数 (根を含む) $O(1)$
pattern_count() パターンの個数 $O(1)$

count・count_each・find_all の文字列や add のパターンは、std::string のほか std::vector<int> など、要素を整数に変換できる列なら何でもかまいません。next・match_count・link と照合の関数は、build の後に呼びます。

find_all は値を返す input iterator を持つ遅延 range です。構築時には入力を読まず、途中で break すると残りの一致を探しません。一致を保存する領域は不要で、列挙状態の追加領域は $O(1)$ です。size()・添字アクセス・逆順走査はありません。

入力が左辺値ならコピーせず参照し、右辺値なら range が所有します。表の構築時間は入力のムーブ・コピーのコストを除きます。走査中はオートマトンと range、および参照している入力を有効なまま保持し、変更しないでください。std::string_view などの参照型を渡した場合は、その参照先も有効である必要があります。通常のコンテナでは、同じ range を繰り返し走査でき、iterator のコピーも独立して進められます。入力自体が単一パスなら、その入力の制約に従います。

保存が必要なら、明示的に vector に変換します。出現回数だけが必要なら count または count_each を使います。

auto matches = ac.find_all(text);
std::vector<decltype(ac)::Match> saved(matches.begin(), matches.end());

関連

Verified with

Code

#pragma once

/**
 * @file aho-corasick.hpp
 * @brief Aho-Corasick
 */

#include <array>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <optional>
#include <type_traits>
#include <utility>
#include <vector>

/**
 * @brief Aho-Corasick (複数のパターンの照合)
 *
 * パターンを add で追加してから build を呼ぶ。文字 c は c - Base として 0 以上 K 未満の番号に直す
 * ノードは Trie と同じく、文字列を追加した順に作った番号を持つ。根はノード 0 (空文字列)
 * 例:
 * AhoCorasick<26, 'a'> ac;
 * ac.add("he");
 * ac.add("she");
 * ac.build();
 * ac.count("ushers");  // 2 ("she" と "he")
 *
 * @tparam K 文字の種類数
 * @tparam Base 最小の文字
 */
template <int K = 26, int Base = 'a'>
class AhoCorasick {
    struct Node {
        std::array<int, K> next;  // build 前は Trie の子 (なければ -1)、build 後は文字を読んだときの遷移先
        int parent, depth;
        int link;         // 失敗リンク (このノードの文字列の、最長の真の接尾辞のノード)
        int out;          // 失敗リンクをたどって最初に着く、パターンが終わるノード (なければ -1)
        int head;         // このノードで終わるパターンの番号のリストの先頭 (なければ -1)
        int match_count;  // このノードの文字列の接尾辞になっているパターンの個数
    };
    // メモリを抑えるため、ノードの中身は int で持つ。外へ返すときに long long にする
    std::vector<Node> nodes;
    std::vector<int> pattern_node, next_pattern;  // パターンの終わるノードと、同じノードで終わる次のパターン
    std::vector<int> bfs_order;
    bool built = false;

    int add_node(int parent, int depth) {
        Node node;
        node.next.fill(-1);
        node.parent = parent;
        node.depth = depth;
        node.link = 0;
        node.out = node.head = -1;
        node.match_count = 0;
        nodes.push_back(node);
        return nodes.size() - 1;
    }
    static int index(int c) {
        assert(0 <= c - Base && c - Base < K);
        return c - Base;
    }

   public:
    AhoCorasick() { add_node(-1, 0); }

    /**
     * @brief パターン s を追加し、パターンの番号 (追加した順に 0, 1, ...) を返す O(|s|)
     * 空でない文字列に限る。同じパターンを何度も追加でき、別のパターンとして数える
     * @param s std::string や std::vector<int> など、要素を整数に変換できる列
     */
    template <typename R>
    long long add(const R& s) {
        assert(!built);
        assert(std::begin(s) != std::end(s));
        int v = 0;
        for (auto c : s) {
            int i = index(c);
            if (nodes[v].next[i] == -1) {
                int u = add_node(v, nodes[v].depth + 1);
                nodes[v].next[i] = u;
            }
            v = nodes[v].next[i];
        }
        int id = pattern_node.size();
        pattern_node.push_back(v);
        next_pattern.push_back(nodes[v].head);
        nodes[v].head = id;
        return id;
    }

    /**
     * @brief 失敗リンクと遷移を作る。パターンを追加し終えてから 1 回だけ呼ぶ O(K * ノード数)
     */
    void build() {
        assert(!built);
        built = true;
        for (int v = 0; v < static_cast<int>(nodes.size()); v++) {
            // 同じノードで終わるパターンのリストを、追加した順に並べ直す
            int rev = -1;
            for (int id = nodes[v].head; id != -1;) {
                int nx = next_pattern[id];
                next_pattern[id] = rev;
                rev = id;
                id = nx;
                nodes[v].match_count++;
            }
            nodes[v].head = rev;
        }
        bfs_order.reserve(nodes.size());
        bfs_order.push_back(0);
        for (int i = 0; i < static_cast<int>(bfs_order.size()); i++) {
            int v = bfs_order[i];
            for (int c = 0; c < K; c++) {
                int u = nodes[v].next[c];
                // まだ -1 なら Trie の子はない。失敗リンク先からの遷移を使う
                if (u == -1) {
                    nodes[v].next[c] = v == 0 ? 0 : nodes[nodes[v].link].next[c];
                    continue;
                }
                int l = v == 0 ? 0 : nodes[nodes[v].link].next[c];
                nodes[u].link = l;
                nodes[u].out = nodes[l].head != -1 ? l : nodes[l].out;
                nodes[u].match_count += nodes[l].match_count;
                bfs_order.push_back(u);
            }
        }
    }

    /**
     * @brief ノードの個数 (根を含む)
     */
    long long size() const { return nodes.size(); }
    /**
     * @brief パターンの個数
     */
    long long pattern_count() const { return pattern_node.size(); }
    /**
     * @brief パターン i が終わるノード
     */
    long long node(long long i) const {
        assert(0 <= i && i < pattern_count());
        return pattern_node[i];
    }
    /**
     * @brief ノード v の親 (根なら -1)
     */
    long long parent(long long v) const { return nodes[v].parent; }
    /**
     * @brief ノード v の深さ (対応する文字列の長さ)
     */
    long long depth(long long v) const { return nodes[v].depth; }

    /**
     * @brief ノード v の失敗リンク (v の文字列の最長の真の接尾辞のうち、ノードのあるもの)。根なら -1
     */
    long long link(long long v) const {
        assert(built);
        return v == 0 ? -1 : nodes[v].link;
    }
    /**
     * @brief ノード v で文字 c を読んだときに移るノード
     */
    long long next(long long v, int c) const {
        assert(built);
        return nodes[v].next[index(c)];
    }
    /**
     * @brief ノード v の文字列の接尾辞になっているパターンの個数 (v に着いたときに終わるパターンの個数)
     */
    long long match_count(long long v) const {
        assert(built);
        return nodes[v].match_count;
    }

    /**
     * @brief text に現れるパターンの個数の合計 (同じパターンが何回現れても、すべて数える) O(|text|)
     */
    template <typename R>
    long long count(const R& text) const {
        assert(built);
        long long res = 0;
        int v = 0;
        for (auto c : text) {
            v = nodes[v].next[index(c)];
            res += nodes[v].match_count;
        }
        return res;
    }
    /**
     * @brief パターンごとに、text に現れる回数を返す O(|text| + ノード数 + パターン数)
     */
    template <typename R>
    std::vector<long long> count_each(const R& text) const {
        assert(built);
        std::vector<long long> visit(nodes.size());
        int v = 0;
        for (auto c : text) {
            v = nodes[v].next[index(c)];
            visit[v]++;
        }
        // 失敗リンクの木で、葉の方から回数を足し上げる
        for (int i = static_cast<int>(bfs_order.size()) - 1; i > 0; i--) {
            int u = bfs_order[i];
            visit[nodes[u].link] += visit[u];
        }
        std::vector<long long> res(pattern_node.size());
        for (int i = 0; i < static_cast<int>(pattern_node.size()); i++) res[i] = visit[pattern_node[i]];
        return res;
    }
    /**
     * @brief find_all が返す、パターンが現れた位置
     */
    struct Match {
        long long pos;  //!< 開始位置
        long long id;   //!< パターンの番号
        friend bool operator==(const Match& a, const Match& b) { return a.pos == b.pos && a.id == b.id; }
        friend bool operator!=(const Match& a, const Match& b) { return !(a == b); }
    };

   private:
    template <typename R>
    class Matches {
        const AhoCorasick* ac;
        R text;
        using Text = std::remove_reference_t<R>;
        using TextIterator = decltype(std::begin(std::declval<const Text&>()));
        using TextSentinel = decltype(std::end(std::declval<const Text&>()));

       public:
        Matches(const AhoCorasick* ac, R&& text) : ac(ac), text(std::forward<R>(text)) {}

        class iterator {
            const AhoCorasick* ac = nullptr;
            // 終端 iterator は入力を持たない。入力 iterator のデフォルト構築は要求しない。
            std::optional<TextIterator> cursor;
            std::optional<TextSentinel> stop;
            long long pos = 0;
            int v = 0, u = -1, id = -1;

           public:
            using value_type = Match;
            using difference_type = std::ptrdiff_t;
            using reference = value_type;
            using pointer = void;
            using iterator_category = std::input_iterator_tag;

            iterator() = default;
            iterator(const AhoCorasick* ac, TextIterator cursor, TextSentinel stop) : ac(ac), cursor(cursor), stop(stop) { ++*this; }
            value_type operator*() const { return {pos - ac->nodes[u].depth, id}; }
            iterator& operator++() {
                if (id != -1) {
                    id = ac->next_pattern[id];
                    if (id != -1) return *this;
                    u = ac->nodes[u].out;
                    if (u != -1) {
                        id = ac->nodes[u].head;
                        return *this;
                    }
                }
                while (*cursor != *stop) {
                    v = ac->nodes[v].next[index(**cursor)];
                    ++*cursor;
                    ++pos;
                    u = ac->nodes[v].head != -1 ? v : ac->nodes[v].out;
                    if (u != -1) {
                        id = ac->nodes[u].head;
                        break;
                    }
                }
                return *this;
            }
            iterator operator++(int) {
                auto previous = *this;
                ++*this;
                return previous;
            }
            bool operator==(const iterator& other) const {
                if (id == -1 || other.id == -1) return id == other.id;
                return ac == other.ac && pos == other.pos && id == other.id;
            }
            bool operator!=(const iterator& other) const { return !(*this == other); }
        };

        iterator begin() const { return iterator(ac, std::begin(std::as_const(text)), std::end(std::as_const(text))); }
        iterator end() const { return iterator(); }
    };

   public:
    /**
     * @brief 一致を Match {pos, id} として遅延列挙する。全走査 O(|text| + 出力の個数)、列挙状態は O(1)
     * 終了位置の昇順。同じ終了位置なら長さの降順、同じ長さならパターン番号の昇順
     * 左辺値の text は参照し、右辺値は所有する
     * @pre 走査が終わるまで、このオートマトンと参照する入力を有効なまま保持すること
     */
    template <typename R>
    auto find_all(R&& text) const {
        assert(built);
        return Matches<R>(this, std::forward<R>(text));
    }
};
#line 2 "src/string/aho-corasick.hpp"

/**
 * @file aho-corasick.hpp
 * @brief Aho-Corasick
 */

#include <array>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <optional>
#include <type_traits>
#include <utility>
#include <vector>

/**
 * @brief Aho-Corasick (複数のパターンの照合)
 *
 * パターンを add で追加してから build を呼ぶ。文字 c は c - Base として 0 以上 K 未満の番号に直す
 * ノードは Trie と同じく、文字列を追加した順に作った番号を持つ。根はノード 0 (空文字列)
 * 例:
 * AhoCorasick<26, 'a'> ac;
 * ac.add("he");
 * ac.add("she");
 * ac.build();
 * ac.count("ushers");  // 2 ("she" と "he")
 *
 * @tparam K 文字の種類数
 * @tparam Base 最小の文字
 */
template <int K = 26, int Base = 'a'>
class AhoCorasick {
    struct Node {
        std::array<int, K> next;  // build 前は Trie の子 (なければ -1)、build 後は文字を読んだときの遷移先
        int parent, depth;
        int link;         // 失敗リンク (このノードの文字列の、最長の真の接尾辞のノード)
        int out;          // 失敗リンクをたどって最初に着く、パターンが終わるノード (なければ -1)
        int head;         // このノードで終わるパターンの番号のリストの先頭 (なければ -1)
        int match_count;  // このノードの文字列の接尾辞になっているパターンの個数
    };
    // メモリを抑えるため、ノードの中身は int で持つ。外へ返すときに long long にする
    std::vector<Node> nodes;
    std::vector<int> pattern_node, next_pattern;  // パターンの終わるノードと、同じノードで終わる次のパターン
    std::vector<int> bfs_order;
    bool built = false;

    int add_node(int parent, int depth) {
        Node node;
        node.next.fill(-1);
        node.parent = parent;
        node.depth = depth;
        node.link = 0;
        node.out = node.head = -1;
        node.match_count = 0;
        nodes.push_back(node);
        return nodes.size() - 1;
    }
    static int index(int c) {
        assert(0 <= c - Base && c - Base < K);
        return c - Base;
    }

   public:
    AhoCorasick() { add_node(-1, 0); }

    /**
     * @brief パターン s を追加し、パターンの番号 (追加した順に 0, 1, ...) を返す O(|s|)
     * 空でない文字列に限る。同じパターンを何度も追加でき、別のパターンとして数える
     * @param s std::string や std::vector<int> など、要素を整数に変換できる列
     */
    template <typename R>
    long long add(const R& s) {
        assert(!built);
        assert(std::begin(s) != std::end(s));
        int v = 0;
        for (auto c : s) {
            int i = index(c);
            if (nodes[v].next[i] == -1) {
                int u = add_node(v, nodes[v].depth + 1);
                nodes[v].next[i] = u;
            }
            v = nodes[v].next[i];
        }
        int id = pattern_node.size();
        pattern_node.push_back(v);
        next_pattern.push_back(nodes[v].head);
        nodes[v].head = id;
        return id;
    }

    /**
     * @brief 失敗リンクと遷移を作る。パターンを追加し終えてから 1 回だけ呼ぶ O(K * ノード数)
     */
    void build() {
        assert(!built);
        built = true;
        for (int v = 0; v < static_cast<int>(nodes.size()); v++) {
            // 同じノードで終わるパターンのリストを、追加した順に並べ直す
            int rev = -1;
            for (int id = nodes[v].head; id != -1;) {
                int nx = next_pattern[id];
                next_pattern[id] = rev;
                rev = id;
                id = nx;
                nodes[v].match_count++;
            }
            nodes[v].head = rev;
        }
        bfs_order.reserve(nodes.size());
        bfs_order.push_back(0);
        for (int i = 0; i < static_cast<int>(bfs_order.size()); i++) {
            int v = bfs_order[i];
            for (int c = 0; c < K; c++) {
                int u = nodes[v].next[c];
                // まだ -1 なら Trie の子はない。失敗リンク先からの遷移を使う
                if (u == -1) {
                    nodes[v].next[c] = v == 0 ? 0 : nodes[nodes[v].link].next[c];
                    continue;
                }
                int l = v == 0 ? 0 : nodes[nodes[v].link].next[c];
                nodes[u].link = l;
                nodes[u].out = nodes[l].head != -1 ? l : nodes[l].out;
                nodes[u].match_count += nodes[l].match_count;
                bfs_order.push_back(u);
            }
        }
    }

    /**
     * @brief ノードの個数 (根を含む)
     */
    long long size() const { return nodes.size(); }
    /**
     * @brief パターンの個数
     */
    long long pattern_count() const { return pattern_node.size(); }
    /**
     * @brief パターン i が終わるノード
     */
    long long node(long long i) const {
        assert(0 <= i && i < pattern_count());
        return pattern_node[i];
    }
    /**
     * @brief ノード v の親 (根なら -1)
     */
    long long parent(long long v) const { return nodes[v].parent; }
    /**
     * @brief ノード v の深さ (対応する文字列の長さ)
     */
    long long depth(long long v) const { return nodes[v].depth; }

    /**
     * @brief ノード v の失敗リンク (v の文字列の最長の真の接尾辞のうち、ノードのあるもの)。根なら -1
     */
    long long link(long long v) const {
        assert(built);
        return v == 0 ? -1 : nodes[v].link;
    }
    /**
     * @brief ノード v で文字 c を読んだときに移るノード
     */
    long long next(long long v, int c) const {
        assert(built);
        return nodes[v].next[index(c)];
    }
    /**
     * @brief ノード v の文字列の接尾辞になっているパターンの個数 (v に着いたときに終わるパターンの個数)
     */
    long long match_count(long long v) const {
        assert(built);
        return nodes[v].match_count;
    }

    /**
     * @brief text に現れるパターンの個数の合計 (同じパターンが何回現れても、すべて数える) O(|text|)
     */
    template <typename R>
    long long count(const R& text) const {
        assert(built);
        long long res = 0;
        int v = 0;
        for (auto c : text) {
            v = nodes[v].next[index(c)];
            res += nodes[v].match_count;
        }
        return res;
    }
    /**
     * @brief パターンごとに、text に現れる回数を返す O(|text| + ノード数 + パターン数)
     */
    template <typename R>
    std::vector<long long> count_each(const R& text) const {
        assert(built);
        std::vector<long long> visit(nodes.size());
        int v = 0;
        for (auto c : text) {
            v = nodes[v].next[index(c)];
            visit[v]++;
        }
        // 失敗リンクの木で、葉の方から回数を足し上げる
        for (int i = static_cast<int>(bfs_order.size()) - 1; i > 0; i--) {
            int u = bfs_order[i];
            visit[nodes[u].link] += visit[u];
        }
        std::vector<long long> res(pattern_node.size());
        for (int i = 0; i < static_cast<int>(pattern_node.size()); i++) res[i] = visit[pattern_node[i]];
        return res;
    }
    /**
     * @brief find_all が返す、パターンが現れた位置
     */
    struct Match {
        long long pos;  //!< 開始位置
        long long id;   //!< パターンの番号
        friend bool operator==(const Match& a, const Match& b) { return a.pos == b.pos && a.id == b.id; }
        friend bool operator!=(const Match& a, const Match& b) { return !(a == b); }
    };

   private:
    template <typename R>
    class Matches {
        const AhoCorasick* ac;
        R text;
        using Text = std::remove_reference_t<R>;
        using TextIterator = decltype(std::begin(std::declval<const Text&>()));
        using TextSentinel = decltype(std::end(std::declval<const Text&>()));

       public:
        Matches(const AhoCorasick* ac, R&& text) : ac(ac), text(std::forward<R>(text)) {}

        class iterator {
            const AhoCorasick* ac = nullptr;
            // 終端 iterator は入力を持たない。入力 iterator のデフォルト構築は要求しない。
            std::optional<TextIterator> cursor;
            std::optional<TextSentinel> stop;
            long long pos = 0;
            int v = 0, u = -1, id = -1;

           public:
            using value_type = Match;
            using difference_type = std::ptrdiff_t;
            using reference = value_type;
            using pointer = void;
            using iterator_category = std::input_iterator_tag;

            iterator() = default;
            iterator(const AhoCorasick* ac, TextIterator cursor, TextSentinel stop) : ac(ac), cursor(cursor), stop(stop) { ++*this; }
            value_type operator*() const { return {pos - ac->nodes[u].depth, id}; }
            iterator& operator++() {
                if (id != -1) {
                    id = ac->next_pattern[id];
                    if (id != -1) return *this;
                    u = ac->nodes[u].out;
                    if (u != -1) {
                        id = ac->nodes[u].head;
                        return *this;
                    }
                }
                while (*cursor != *stop) {
                    v = ac->nodes[v].next[index(**cursor)];
                    ++*cursor;
                    ++pos;
                    u = ac->nodes[v].head != -1 ? v : ac->nodes[v].out;
                    if (u != -1) {
                        id = ac->nodes[u].head;
                        break;
                    }
                }
                return *this;
            }
            iterator operator++(int) {
                auto previous = *this;
                ++*this;
                return previous;
            }
            bool operator==(const iterator& other) const {
                if (id == -1 || other.id == -1) return id == other.id;
                return ac == other.ac && pos == other.pos && id == other.id;
            }
            bool operator!=(const iterator& other) const { return !(*this == other); }
        };

        iterator begin() const { return iterator(ac, std::begin(std::as_const(text)), std::end(std::as_const(text))); }
        iterator end() const { return iterator(); }
    };

   public:
    /**
     * @brief 一致を Match {pos, id} として遅延列挙する。全走査 O(|text| + 出力の個数)、列挙状態は O(1)
     * 終了位置の昇順。同じ終了位置なら長さの降順、同じ長さならパターン番号の昇順
     * 左辺値の text は参照し、右辺値は所有する
     * @pre 走査が終わるまで、このオートマトンと参照する入力を有効なまま保持すること
     */
    template <typename R>
    auto find_all(R&& text) const {
        assert(built);
        return Matches<R>(this, std::forward<R>(text));
    }
};
Back to top page