sirkit-cpp-library

競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。

View the Project on GitHub reinsirk/sirkit-cpp-library

Suffix Automaton

String/Suffix_Automaton.cpp · ソース · 文書 Last Commit

通常版・コンパイラ共通 · この版の一覧へ

通常版・GCC専用 · この版の一覧へ

通常版・Clang専用 · この版の一覧へ

通常版・MSVC専用 · この版の一覧へ

速度優先版・コンパイラ共通 · この版の一覧へ

速度優先版・GCC専用 · この版の一覧へ

速度優先版・Clang専用 · この版の一覧へ

速度優先版・MSVC専用 · この版の一覧へ

SuffixAutomatonは文字列の末尾に文字を追加しながら、部分文字列が存在するか、何回現れるか、異なる部分文字列がいくつあるかを照会できます。最長共通部分文字列も求められます。既定のSuffixAutomaton<>は英小文字、SuffixAutomaton<256,0>はNULを含む全バイト値を扱います。一般形は<Alphabet,Base>で、値を[Base,Base+Alphabet)に収めます。処理の単位はバイトです。使用例を参照してください。

以下、nは現在の文字列長、mは追加列または照会列の長さ、statesは状態数です。

API

SuffixAutomaton

SuffixAutomaton();
explicit SuffixAutomaton(std::string_view text);
SuffixAutomaton(const SuffixAutomaton&);
SuffixAutomaton(SuffixAutomaton&&other) noexcept;

空の状態を作るか、指定した文字列、コピー、所有権の移動で構築します。コピーは元の状態から独立します。

制約: 1<=Alphabet<=256、Base+Alphabet<=256、文字列は指定バイト範囲内。

計算量: 空とmoveはO(1)、文字列長mにO(Alphabet*m)、コピーは保持領域に比例。

operator=

SuffixAutomaton& operator=(const SuffixAutomaton&other);
SuffixAutomaton&operator=(SuffixAutomaton&&other)noexcept;

独立コピー/所有権移動で代入し、自身への参照を返します。

制約: 同じ型の個体。

計算量: コピーは新旧保持領域に比例。move代入は旧状態の破棄を含みます。

append

void append(std::uint8_t byte);
void append(std::string_view text);

末尾へバイト/列を追加します。

制約: 追加するバイトは[Base,Base+Alphabet)。番号・長さ・容量の上限以下。

計算量: 1バイトは償却O(Alphabet)、最悪O(n+Alphabet)。mバイトの追加はO(Alphabet*m)。

size

std::size_t size()const noexcept;

元の文字列長を返します。

制約: 追加の制約はありません。

計算量: O(1)。

empty

bool empty()const noexcept;

空ならtrueです。

制約: 追加の制約はありません。

計算量: O(1)。

distinct_substring_count

std::uint64_t distinct_substring_count()const noexcept;

空を除く異なる部分文字列の個数を返します。

制約: 追加の制約はありません。

計算量: O(1)。

state_count

std::size_t state_count()const noexcept;

保存する状態数を返します。

制約: 追加の制約はありません。

計算量: O(1)。

contains

bool contains(std::string_view pattern)const noexcept;

部分文字列として存在すればtrueです。空語も含みます。

制約: 範囲外バイトは不一致として扱います。

計算量: パターン長mにO(m+1)。

occurrences

std::uint64_t occurrences(std::string_view pattern)const;

重なりを含む出現回数を返します。空語はn+1です。

制約: 範囲外バイトは不一致として扱います。同じ個体の並行キャッシュ照会は外部同期が必要です。

計算量: append後の最初の一致する非空照会はO(n+states+m)、以後O(m+1)。

longest_common_substring

Match longest_common_substring(std::string_view text)const noexcept;

最長共通部分文字列のMatch{first_start,second_start,length}を返します。

制約: 引数の範囲外バイトは一致を区切ります。

計算量: 引数長mにO(m+1)。

reserve

void reserve(std::size_t text_capacity);

指定した文字列長で必要となる最大状態数と関連領域を予約します。

制約: 番号・容量の上限以下。

計算量: 再確保時は保持する状態・文字列・キャッシュ等の大きさに比例する上界。

reset

void reset(std::string_view text={});

指定した文字列へ置換します。省略すると空です。

制約: 追加するバイトは[Base,Base+Alphabet)。番号・長さ・容量の上限以下。

計算量: 旧状態の解放と新長mにO(Alphabet*m+旧保持量+1)の上界。

clear

void clear()noexcept;

空へ戻し、全領域を解放します。

制約: 既存の借用viewや状態番号を再利用しないこと。

計算量: O(n+1)。

swap

void swap(SuffixAutomaton&other)noexcept;
void swap(SuffixAutomaton&a,SuffixAutomaton&b)noexcept;

内容と所有領域を交換します。

制約: 追加の制約はありません。

計算量: O(1)。

SuffixAutomaton<> automaton("ababa");
auto distinct = automaton.distinct_substring_count(); // 9。
auto count = automaton.occurrences("aba"); // 2。
auto match = automaton.longest_common_substring("zzbabab");
// first_start=1、second_start=2、length=4("baba")。

最長共通部分文字列の位置は自分側と引数側の順です。同長なら引数で先に終わるものを選び、長さ0なら位置も0です。元の文字列自体は保持せず、状態から自分側の位置を復元します。範囲外バイトの検索は不一致、最長共通部分文字列ではその位置で一致を区切ります。

計算量・所有と検査

同じ終了位置を持つ部分文字列を状態へまとめ、必要な場合に状態を複製します。1バイト追加は償却O(Alphabet)、1回の最悪はO(n+Alphabet)です。固定Alphabetなら償却O(1)。状態数は高々2n+1、領域はO(Alphabet*states+n+1)で、空なら根も確保しません。

append後に空でない列が初めて一致した照会で、出現回数のキャッシュを作ります。この照会はO(n+states+m)、以後はO(m)です。領域の確保に失敗しても元の状態を保ちます。const照会もキャッシュを更新するため、同じ個体への並行キャッシュ照会は外部で同期してください。

コピーは独立、コピー代入・resetは失敗時に元を保ちます。moveはnoexcept・O(1)、移動元は空で再利用可です。1バイト追加は強い例外保証、文字列追加も確保・容量超過では不変ですが、途中の不正バイトでは処理済みの接頭辞を保持します。検査だけの全走査はしません。

SKIP_RUNTIME_CHECKSは追加バイトの検査を除き、照会の不一致判定とint32_t状態番号・長さ・容量の保護は維持します。構成・機能の数学的参考はNyaanのSuffix Automatonで、固定幅配列と出現回数キャッシュは独立に実装しています。

ソースのAPI注記
[SuffixAutomaton<Alphabet=26,Base='a'>] 連続するbyte値[Base,Base+Alphabet)のSuffix Automaton。1<=Alphabet<=256、Base+Alphabet<=256。
SuffixAutomaton()/SuffixAutomaton(string_view): 空/与えた文字列で構築。byte単位、Unicode文字単位ではない。
append(uint8_t)/append(string_view): 末尾へ追加。固定Alphabetで償却O(Alphabet)/O(Alphabet*m)、1byte追加は最悪O(n+Alphabet)。
確保を先行し1byte追加は強い例外保証。文字列版の確保失敗では変更せず、途中の不正byteでは処理済み接頭辞を保持。
contains(pattern): 部分文字列か。空はtrue。occurrences(pattern): 重なる出現回数、空はn+1。範囲外byteを含む照会は不一致。
containsはO(m)。occurrencesはappend後の最初の一致照会でO(n+states+m)、以後O(m)。出現回数はconstな遅延キャッシュを使う。
longest_common_substring(text): Match{first_start,second_start,length}。自分/引数側の開始位置と長さ、最長が複数なら引数で先に終わるもの。O(m)。
size()/empty()/state_count()/distinct_substring_count(): 元の長さ/空か/保存状態数/空を除く相異なる部分文字列数。O(1)。空は状態を確保しない。
reserve(text_capacity): その長さの最悪状態数を予約、必要ならO(Alphabet*states)。reset(text={}): 新しい文字列へ置換、強い例外保証。
clear(): 空へ戻して全領域を解放、O(states+n+1)。swap: O(1)。コピーは独立、コピー代入は強い例外保証。
moveはnoexcept・O(1)、移動元は空で再利用可能。領域はO(Alphabet*states+n+1)、states<=2*n+1。
入力byte検査はSKIP_RUNTIME_CHECKSで除く。照会の不一致判定と、int32_t状態番号/長さ・容量の保護は常に維持。
キャッシュ構築の確保失敗は文字列・オートマトンを保つ。同じ個体への並行したキャッシュ照会は外部で同期する。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Number of Substrings suffix_automaton.cpp 未提出 —
Longest Common Substring suffix_automaton_lcs.cpp 未提出 —

✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。

ローカル・CI検査

検査 状態
正常系 未実施
失敗系 未測定
Library Checker公式ケース 未測定
性能測定 未実施
ASan/UBSan 未実施
カバレッジ 未実施

到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。

実行条件・件数・測定結果 · 結果JSON

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// 参考(数学的構成・機能): https://nyaannyaan.github.io/library/string/suffix-automaton.hpp.html
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/suffix_automaton.md
//
// API一覧
// [SuffixAutomaton<Alphabet=26,Base='a'>] 連続するbyte値[Base,Base+Alphabet)のSuffix Automaton。1<=Alphabet<=256、Base+Alphabet<=256。
// SuffixAutomaton()/SuffixAutomaton(string_view): 空/与えた文字列で構築。byte単位、Unicode文字単位ではない。
// append(uint8_t)/append(string_view): 末尾へ追加。固定Alphabetで償却O(Alphabet)/O(Alphabet*m)、1byte追加は最悪O(n+Alphabet)。
// 確保を先行し1byte追加は強い例外保証。文字列版の確保失敗では変更せず、途中の不正byteでは処理済み接頭辞を保持。
// contains(pattern): 部分文字列か。空はtrue。occurrences(pattern): 重なる出現回数、空はn+1。範囲外byteを含む照会は不一致。
// containsはO(m)。occurrencesはappend後の最初の一致照会でO(n+states+m)、以後O(m)。出現回数はconstな遅延キャッシュを使う。
// longest_common_substring(text): Match{first_start,second_start,length}。自分/引数側の開始位置と長さ、最長が複数なら引数で先に終わるもの。O(m)。
// size()/empty()/state_count()/distinct_substring_count(): 元の長さ/空か/保存状態数/空を除く相異なる部分文字列数。O(1)。空は状態を確保しない。
// reserve(text_capacity): その長さの最悪状態数を予約、必要ならO(Alphabet*states)。reset(text={}): 新しい文字列へ置換、強い例外保証。
// clear(): 空へ戻して全領域を解放、O(states+n+1)。swap: O(1)。コピーは独立、コピー代入は強い例外保証。
// moveはnoexcept・O(1)、移動元は空で再利用可能。領域はO(Alphabet*states+n+1)、states<=2*n+1。
// 入力byte検査はSKIP_RUNTIME_CHECKSで除く。照会の不一致判定と、int32_t状態番号/長さ・容量の保護は常に維持。
// キャッシュ構築の確保失敗は文字列・オートマトンを保つ。同じ個体への並行したキャッシュ照会は外部で同期する。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <string_view>
#include <utility>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_STRING_TREE_CAPACITY_DEFINED
#define SIRKIT_STRING_TREE_CAPACITY_DEFINED
namespace detail {
inline std::size_t StringTreeGrowth(std::size_t capacity, std::size_t required, std::size_t limit) {
    return std::max(required, capacity > limit / 2 ? limit : capacity * 2);
}

inline void CheckStringTreeSlots(std::size_t count, std::size_t available, std::size_t roots,
                                 std::size_t nodes_per_char, const char* error) {
    if (count > (available - std::min(roots, available)) / nodes_per_char)
        throw std::length_error(error);
}
}
#endif
#ifndef SIRKIT_SUFFIX_AUTOMATON_DEFINED
#define SIRKIT_SUFFIX_AUTOMATON_DEFINED
template<std::size_t Alphabet=26,std::uint16_t Base='a'>
class SuffixAutomaton {
    static_assert(Alphabet>0&&Alphabet<=256&&Base<256&&Alphabet<=256-Base);
    using Index=std::int32_t;
    struct State {
        std::array<Index,Alphabet> next;
        Index link=-1,length=0,first_end=0;
        bool terminal=false;
        State(){next.fill(-1);}
    };
    std::vector<State> states_;
    std::size_t length_=0;
    Index last_=0;
    std::uint64_t distinct_=0;
    mutable std::vector<std::uint64_t> counts_;
    mutable bool counts_valid_=false;
    static constexpr std::size_t index_limit=static_cast<std::size_t>(std::numeric_limits<Index>::max());
    void prepare_append(std::size_t count) {
        if(count==0)return;
        if(count>index_limit-length_)throw std::length_error("SuffixAutomaton: length");
        const auto limit=std::min(index_limit,states_.max_size());
        const std::size_t root=states_.empty()?1:0;
        detail::CheckStringTreeSlots(count, limit - states_.size(), root, 2, "SuffixAutomaton: states");
        const auto required=states_.size()+root+2*count;
        if(states_.capacity()<required) states_.reserve(detail::StringTreeGrowth(states_.capacity(), required, limit));
    }
    static void check_byte(std::uint8_t byte) {
#ifndef SKIP_RUNTIME_CHECKS
        if(byte<Base || static_cast<std::size_t>(byte-Base)>=Alphabet)throw std::invalid_argument("SuffixAutomaton: byte");
#else
        (void)byte;
#endif
    }
    void append_prepared(std::uint8_t byte) {
        const auto key=static_cast<std::size_t>(byte)-Base;
        if(states_.empty())states_.emplace_back();
        const Index current=static_cast<Index>(states_.size());
        states_.emplace_back();states_[current].length=static_cast<Index>(length_+1);states_[current].first_end=static_cast<Index>(length_);states_[current].terminal=true;
        Index p=last_;
        while(p!=-1&&states_[p].next[key]==-1){states_[p].next[key]=current;p=states_[p].link;}
        if(p==-1)states_[current].link=0;
        else {
            const Index q=states_[p].next[key];
            if(states_[p].length+1==states_[q].length)states_[current].link=q;
            else {
                const Index clone=static_cast<Index>(states_.size());
                states_.push_back(states_[q]);states_[clone].length=states_[p].length+1;states_[clone].terminal=false;
                while(p!=-1&&states_[p].next[key]==q){states_[p].next[key]=clone;p=states_[p].link;}
                states_[q].link=states_[current].link=clone;
            }
        }
        distinct_+=static_cast<std::uint64_t>(states_[current].length-states_[states_[current].link].length);
        last_=current;++length_;counts_valid_=false;
    }
    Index find(std::string_view text) const noexcept {
        Index current=0;
        for(unsigned char byte:text){
            if(byte<Base||static_cast<std::size_t>(byte-Base)>=Alphabet||states_.empty())return -1;
            current=states_[current].next[static_cast<std::size_t>(byte)-Base];if(current==-1)return -1;
        }
        return current;
    }
    void build_counts() const {
        if(counts_valid_)return;
        std::vector<std::uint64_t> counts(states_.size());
        std::vector<Index> order(states_.size());
        std::vector<std::uint32_t> buckets(length_+1);
        for(const auto&state:states_)++buckets[static_cast<std::size_t>(state.length)];
        for(std::size_t i=1;i<buckets.size();++i)buckets[i]+=buckets[i-1];
        for(std::size_t i=0;i<states_.size();++i){order[--buckets[static_cast<std::size_t>(states_[i].length)]]=static_cast<Index>(i);counts[i]=states_[i].terminal?1:0;}
        for(std::size_t i=order.size();i>0;--i){const Index v=order[i-1];if(states_[v].link!=-1)counts[states_[v].link]+=counts[v];}
        counts_.swap(counts);counts_valid_=true;
    }
public:
    struct Match {std::size_t first_start=0,second_start=0,length=0;};
    SuffixAutomaton()=default;
    explicit SuffixAutomaton(std::string_view text){append(text);}
    SuffixAutomaton(const SuffixAutomaton&)=default;
    SuffixAutomaton& operator=(const SuffixAutomaton&other){if(this!=&other){SuffixAutomaton next(other);swap(next);}return *this;}
    SuffixAutomaton(SuffixAutomaton&&other) noexcept
        :states_(std::move(other.states_)),length_(std::exchange(other.length_,0)),last_(std::exchange(other.last_,0)),distinct_(std::exchange(other.distinct_,0)),counts_(std::move(other.counts_)),counts_valid_(std::exchange(other.counts_valid_,false)){other.states_.clear();other.counts_.clear();}
    SuffixAutomaton&operator=(SuffixAutomaton&&other)noexcept{if(this!=&other){SuffixAutomaton next(std::move(other));swap(next);}return *this;}
    void swap(SuffixAutomaton&other)noexcept{using std::swap;states_.swap(other.states_);swap(length_,other.length_);swap(last_,other.last_);swap(distinct_,other.distinct_);counts_.swap(other.counts_);swap(counts_valid_,other.counts_valid_);}
    friend void swap(SuffixAutomaton&a,SuffixAutomaton&b)noexcept{a.swap(b);}
    std::size_t size()const noexcept{return length_;}
    bool empty()const noexcept{return length_==0;}
    std::size_t state_count()const noexcept{return states_.size();}
    std::uint64_t distinct_substring_count()const noexcept{return distinct_;}
    void reserve(std::size_t text_capacity){if(text_capacity<=length_)return;prepare_append(text_capacity-length_);}
    void append(std::uint8_t byte){check_byte(byte);prepare_append(1);append_prepared(byte);}
    void append(std::string_view text){prepare_append(text.size());for(unsigned char byte:text){check_byte(byte);append_prepared(byte);}}
    bool contains(std::string_view pattern)const noexcept{return find(pattern)!=-1;}
    std::uint64_t occurrences(std::string_view pattern)const {
        if(pattern.empty())return static_cast<std::uint64_t>(length_)+1;
        const auto state=find(pattern);if(state==-1)return 0;build_counts();return counts_[state];
    }
    Match longest_common_substring(std::string_view text)const noexcept {
        Match best;Index current=0;std::size_t matched=0;
        for(std::size_t i=0;i<text.size();++i){const auto byte=static_cast<unsigned char>(text[i]);
            if(states_.empty()||byte<Base||static_cast<std::size_t>(byte-Base)>=Alphabet){current=0;matched=0;continue;}
            const auto key=static_cast<std::size_t>(byte)-Base;
            while(current!=0&&states_[current].next[key]==-1){current=states_[current].link;matched=static_cast<std::size_t>(states_[current].length);}
            if(states_[current].next[key]!=-1){current=states_[current].next[key];++matched;}else matched=0;
            if(matched>best.length)best={static_cast<std::size_t>(states_[current].first_end)+1-matched,i+1-matched,matched};
        }
        return best;
    }
    void clear()noexcept{std::vector<State>{}.swap(states_);std::vector<std::uint64_t>{}.swap(counts_);length_=0;last_=0;distinct_=0;counts_valid_=false;}
    void reset(std::string_view text={}){SuffixAutomaton next(text);swap(next);}
};
#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1
Back to top page