競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
文字列の接尾辞を、共通する先頭部分でまとめた圧縮トライです。辺をたどると部分文字列の共通接頭辞と、その出現位置を確認できます。
SuffixTreeexplicit SuffixTree(std::string_view text)
文字列をコピーして木を作ります。根は頂点0です。空接尾辞は登録せず、空文字列の木には根だけがあります。文字列長を $n$ として、$O(n+1)$ 時間・領域です。長さの上限は (INT_MAX-1)/2 です。コピーした個体は同じ木を所有します。
取得したビューは参照先の木を所有する個体が生きている間に使えます。文字の比較には符号なしバイトの値を使い、位置と頂点番号は0始まりです。
nodesstd::span<const Node> nodes() const noexcept
頂点番号順の一覧を $O(1)$ 時間で参照します。各頂点は次の値を持ちます。
parent は親の番号で、根では -1 です。depth は根からの文字数です。suffix_start はその頂点で終わる接尾辞の開始位置です。終わるものがなければ -1 です。first_suffix と last_suffix は接尾辞配列での半開区間です。自分と子孫で終わる接尾辞を含みます。childrenstd::span<const int> children(int vertex) const
子の頂点番号を辺ラベルの辞書順で参照します。ビューの取得は $O(1)$ 時間です。
suffixesstd::span<const int> suffixes(int vertex) const
その頂点で終わる接尾辞と子孫で終わる接尾辞の開始位置を、接尾辞の辞書順で参照します。ビューの取得は $O(1)$ 時間です。
edge_labelstd::string_view edge_label(int vertex) const
親からその頂点へ向かう辺に対応する文字列を参照します。根では空のビューを返します。ビューの取得は $O(1)$ 時間です。
longest_nonoverlapping_repeatRepeat longest_nonoverlapping_repeat() const
重ならずに2回現れる最長部分文字列を $O(n+1)$ 時間・追加領域で求めます。first_start と second_start は出現位置、length は長さです。該当する非空文字列がなければすべて0を返します。
const sirkit::SuffixTree tree("bananabanana");
const auto repeat = tree.longest_nonoverlapping_repeat();
assert(repeat.length == 6);
[SuffixTree] 非空接尾辞の圧縮トライ。文字列を所有し、根は頂点0。文字列長nは(INT_MAX-1)/2以下。
SuffixTree(text): O(n+1)時間・領域で構築。コピーは木を共有する。
nodes(): Node{parent,depth,suffix_start,first_suffix,last_suffix}の頂点番号順ビュー。根のparentは-1。
depthは根からの文字数、suffix_startはその頂点で終わる接尾辞の開始位置(なければ-1)。
first_suffix/last_suffixは辞書順の接尾辞配列内の子孫範囲(半開区間、頂点自身の接尾辞も含む)。
children(vertex): 子の頂点番号を辺ラベルの辞書順で返すビュー。suffixes(vertex): 子孫の接尾辞の開始位置を辞書順で返すビュー。
edge_label(vertex): 親からの辺ラベルを参照するビュー。根では空。各ビュー取得はO(1)時間。頂点番号はnodes()の添字。
longest_nonoverlapping_repeat(): 重ならず2回現れる最長の部分文字列をRepeat{first_start,second_start,length}で返す。
該当する非空部分文字列がなければ各値0。O(n+1)時間・追加領域。文字の順序は符号なしバイト順。
ビューは木を共有する個体が少なくとも一つ生きている間に使う。
[同梱の接尾辞配列]
suffix_array(const std::string&)/suffix_array(string_view): 符号なしバイトの辞書順で接尾辞の開始位置を返す。空接尾辞は含めない。
C文字列のsuffix_array(char*/const char*)も可。終端あり・nullptr不可。文字列を複製しない。
suffix_array(vector<int>, upper): 全要素0..upperの整数列。SA-ISでO(n+upper)時間・領域。
suffix_array<T>(const vector<T>&): Tの<で圧縮して構築。負数/uint64_t最大値も可、O(n log n)時間・O(n)領域。
upperは0以上INT_MAX-1未満。文字列版はO(n)時間・領域。全版で列長はINT_MAX-1未満、空なら{}。返却添字はint。
lcp_array(const string&,sa)/lcp_array<T>(const vector<T>&,sa): 隣り合う接尾辞の共通接頭辞長を返す。n<2なら{}、それ以外はn-1個。O(n)時間・領域。
追加のlcp_array(sequence,sa)はstring_view/array等にも対応。
lcp_arrayのsaはsの正しい接尾辞配列が前提。既定検査はサイズ・添字・重複を確認し、辞書順までは再検査しない。
SuffixArrayEqualRange(s,sa,pattern): patternを接頭辞に持つ接尾辞のsa内半開区間を返す。
検索はO((m+1)log(n+1))時間・追加O(1)。string_view版は符号なしバイト順、整数vector版はTの順序。
各比較/添字アクセスがO(1)の場合の計算量。Tの<は一貫した順序が前提。
空patternは全接尾辞に一致。検索はsaの妥当性を全走査せず、実際に参照する添字だけ検査する。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Who Says a Pun? | suffix_tree_nonoverlapping_repeat.cpp | 未提出 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/suffix_tree.md
//
// API一覧
// [SuffixTree] 非空接尾辞の圧縮トライ。文字列を所有し、根は頂点0。文字列長nは(INT_MAX-1)/2以下。
// SuffixTree(text): O(n+1)時間・領域で構築。コピーは木を共有する。
// nodes(): Node{parent,depth,suffix_start,first_suffix,last_suffix}の頂点番号順ビュー。根のparentは-1。
// depthは根からの文字数、suffix_startはその頂点で終わる接尾辞の開始位置(なければ-1)。
// first_suffix/last_suffixは辞書順の接尾辞配列内の子孫範囲(半開区間、頂点自身の接尾辞も含む)。
// children(vertex): 子の頂点番号を辺ラベルの辞書順で返すビュー。suffixes(vertex): 子孫の接尾辞の開始位置を辞書順で返すビュー。
// edge_label(vertex): 親からの辺ラベルを参照するビュー。根では空。各ビュー取得はO(1)時間。頂点番号はnodes()の添字。
// longest_nonoverlapping_repeat(): 重ならず2回現れる最長の部分文字列をRepeat{first_start,second_start,length}で返す。
// 該当する非空部分文字列がなければ各値0。O(n+1)時間・追加領域。文字の順序は符号なしバイト順。
// ビューは木を共有する個体が少なくとも一つ生きている間に使う。
//
// [同梱の接尾辞配列]
// suffix_array(const std::string&)/suffix_array(string_view): 符号なしバイトの辞書順で接尾辞の開始位置を返す。空接尾辞は含めない。
// C文字列のsuffix_array(char*/const char*)も可。終端あり・nullptr不可。文字列を複製しない。
// suffix_array(vector<int>, upper): 全要素0..upperの整数列。SA-ISでO(n+upper)時間・領域。
// suffix_array<T>(const vector<T>&): Tの<で圧縮して構築。負数/uint64_t最大値も可、O(n log n)時間・O(n)領域。
// upperは0以上INT_MAX-1未満。文字列版はO(n)時間・領域。全版で列長はINT_MAX-1未満、空なら{}。返却添字はint。
// lcp_array(const string&,sa)/lcp_array<T>(const vector<T>&,sa): 隣り合う接尾辞の共通接頭辞長を返す。n<2なら{}、それ以外はn-1個。O(n)時間・領域。
// 追加のlcp_array(sequence,sa)はstring_view/array等にも対応。
// lcp_arrayのsaはsの正しい接尾辞配列が前提。既定検査はサイズ・添字・重複を確認し、辞書順までは再検査しない。
// SuffixArrayEqualRange(s,sa,pattern): patternを接頭辞に持つ接尾辞のsa内半開区間を返す。
// 検索はO((m+1)log(n+1))時間・追加O(1)。string_view版は符号なしバイト順、整数vector版はTの順序。
// 各比較/添字アクセスがO(1)の場合の計算量。Tの<は一貫した順序が前提。
// 空patternは全接尾辞に一致。検索はsaの妥当性を全走査せず、実際に参照する添字だけ検査する。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <span>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include <numeric>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_SUFFIX_ARRAY_DETAIL_DEFINED
#define SIRKIT_SUFFIX_ARRAY_DETAIL_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
inline void suffix_length_check(std::size_t n) {
if (n >= static_cast<std::size_t>(std::numeric_limits<int>::max() - 1))
throw std::length_error("suffix_array: sequence too long");
}
// 正の整数列に一意な終端0を付けた列を扱う。再帰先にも終端0を残す。
template<class Symbol> std::vector<int> suffix_induced(std::span<const Symbol> symbols, int alphabet) {
const int n = static_cast<int>(symbols.size());
if (n == 1) return {0};
// 0=L型、1=S型、3=LMS。隣接2位置の型を決めてから境界印を重ねる。
std::vector<std::uint8_t> small(n);
std::vector<int> selected;
selected.reserve(static_cast<std::size_t>(n / 2));
std::vector<int> starts(static_cast<std::size_t>(alphabet) + 1), ends(starts.size());
++ends[symbols[n - 1]];
small[n - 1] = 1;
for (int i = n - 2; i >= 0; --i) {
++ends[symbols[i]];
small[i] = symbols[i] < symbols[i + 1] ||
(symbols[i] == symbols[i + 1] && small[i + 1]);
if (!small[i] && small[i + 1]) { small[i + 1] |= 2; selected.push_back(i + 1); }
}
std::reverse(selected.begin(), selected.end());
int total = 0;
for (int symbol = 0; symbol <= alphabet; ++symbol) {
starts[symbol] = total; total += ends[symbol]; ends[symbol] = total;
}
std::vector<int> suffixes(n, -1), cursor(ends.size());
const auto induce = [&](const std::vector<int>& order, bool clear) {
if (clear) std::fill(suffixes.begin(), suffixes.end(), -1);
cursor = ends;
for (auto it = order.rbegin(); it != order.rend(); ++it)
suffixes[--cursor[symbols[*it]]] = *it;
cursor = starts;
for (int slot = 0; slot < n; ++slot) {
const int before = suffixes[slot] - 1;
if (before >= 0 && !small[before])
suffixes[cursor[symbols[before]]++] = before;
}
cursor = ends;
for (int slot = n - 1; slot >= 0; --slot) {
const int before = suffixes[slot] - 1;
if (before >= 0 && small[before])
suffixes[--cursor[symbols[before]]] = before;
}
};
induce(selected, false);
const int count = static_cast<int>(selected.size());
// LMSが終端だけなら、再誘導しても同じ順序になる。
if (count == 1) return suffixes;
std::vector<int> reduced(count);
// LMSは隣接しないため位置/2が一意。LMSの欄だけ設定・参照する。
auto selected_id = std::make_unique_for_overwrite<int[]>(static_cast<std::size_t>((n + 1) / 2));
for (int i = 0; i < count; ++i) selected_id[selected[i] / 2] = i;
int previous = -1, name = -1;
for (int position : suffixes) {
if ((small[position] & 2) == 0) continue;
bool different = previous < 0;
if (!different) {
int offset = 0;
for (;;) {
if (symbols[position + offset] != symbols[previous + offset] ||
small[position + offset] != small[previous + offset]) {
different = true; break;
}
// 種別フラグが一致済みなので、両方が同時に次のLMSへ達する。
if (offset > 0 && (small[position + offset] & 2)) break;
++offset;
}
}
if (different) ++name;
reduced[selected_id[position / 2]] = name;
previous = position;
}
selected_id.reset();
const bool distinct_names = name + 1 == count;
auto reduced_order = distinct_names ? std::vector<int>(count) : suffix_induced(std::span<const int>(reduced), name);
if (distinct_names) {
for (int i = 0; i < count; ++i) reduced_order[reduced[i]] = i;
}
for (int& position : reduced_order) position = selected[position];
induce(reduced_order, true);
return suffixes;
}
inline std::vector<int> suffix_string(std::string_view s) {
/*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_length_check(s.size());
auto encoded = std::make_unique_for_overwrite<std::uint16_t[]>(s.size() + 1);
encoded[s.size()] = 0;
for (std::size_t i = 0; i < s.size(); ++i) encoded[i] = static_cast<std::uint16_t>(static_cast<unsigned char>(s[i]) + 1);
auto result = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_induced(std::span<const std::uint16_t>(encoded.get(), s.size() + 1), 256);
result.erase(result.begin());
return result;
}
template <class Sequence, class Pattern, class Convert>
std::pair<int, int> suffix_search(const Sequence& s, const std::vector<int>& sa,
const Pattern& pattern, Convert convert) {
suffix_length_check(s.size());
#ifndef SKIP_RUNTIME_CHECKS
if (sa.size() != s.size()) throw std::invalid_argument("SuffixArrayEqualRange: size");
#endif
const auto compare = [&](int slot) {
const int position = sa[slot];
#ifndef SKIP_RUNTIME_CHECKS
if (position < 0 || static_cast<std::size_t>(position) >= s.size())
throw std::out_of_range("SuffixArrayEqualRange: suffix index");
#endif
std::size_t offset = 0;
const std::size_t remaining = s.size() - static_cast<std::size_t>(position);
while (offset < pattern.size() && offset < remaining) {
const auto a = convert(s[static_cast<std::size_t>(position) + offset]);
const auto b = convert(pattern[offset]);
if (a < b) return -1;
if (b < a) return 1;
++offset;
}
return offset == pattern.size() ? 0 : -1;
};
int first = 0, last = static_cast<int>(sa.size());
while (first < last) {
const int middle = first + (last - first) / 2;
if (compare(middle) < 0) first = middle + 1; else last = middle;
}
const int lower = first;
last = static_cast<int>(sa.size());
while (first < last) {
const int middle = first + (last - first) / 2;
if (compare(middle) <= 0) first = middle + 1; else last = middle;
}
return {lower, first};
}
}
#endif
#ifndef SIRKIT_SUFFIX_ARRAY_DEFINED
#define SIRKIT_SUFFIX_ARRAY_DEFINED
inline std::vector<int> suffix_array(const std::string& s) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_string(s);
}
template<class View> requires std::same_as<View, std::string_view>
std::vector<int> suffix_array(View s) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_string(s);
}
template<class Char> requires (std::same_as<Char, char> || std::same_as<Char, const char>)
std::vector<int> suffix_array(Char* s) {
#ifndef SKIP_RUNTIME_CHECKS
if (s == nullptr) throw std::invalid_argument("suffix_array: null text");
#endif
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_string(std::string_view(s));
}
inline std::vector<int> suffix_array(const std::vector<int>& s, int upper) {
/*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_length_check(s.size());
if (upper < 0 || upper >= std::numeric_limits<int>::max() - 1)
throw std::length_error("suffix_array: alphabet too large");
std::vector<int> encoded(s.size() + 1);
for (std::size_t i = 0; i < s.size(); ++i) {
#ifndef SKIP_RUNTIME_CHECKS
if (s[i] < 0 || s[i] > upper) throw std::out_of_range("suffix_array: symbol");
#endif
encoded[i] = s[i] + 1;
}
auto result = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_induced(std::span<const int>(encoded), upper + 1);
result.erase(result.begin());
return result;
}
template <class T>
std::vector<int> suffix_array(const std::vector<T>& s) {
/*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_length_check(s.size());
// 先頭要素の同値類がn個なら、その順序だけで接尾辞順が決まる。
if constexpr (std::integral<T>) {
std::vector<T> alphabet = s;
std::sort(alphabet.begin(), alphabet.end());
alphabet.erase(std::unique(alphabet.begin(), alphabet.end()), alphabet.end());
if (alphabet.size() == s.size()) {
std::vector<int> result(s.size());
for (std::size_t i = 0; i < s.size(); ++i)
result[std::lower_bound(alphabet.begin(), alphabet.end(), s[i]) - alphabet.begin()] = static_cast<int>(i);
return result;
}
std::vector<int> encoded(s.size() + 1);
for (std::size_t i = 0; i < s.size(); ++i)
encoded[i] = static_cast<int>(std::lower_bound(alphabet.begin(), alphabet.end(), s[i]) - alphabet.begin()) + 1;
auto result = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_induced(std::span<const int>(encoded), static_cast<int>(alphabet.size()));
result.erase(result.begin());
return result;
} else {
std::vector<int> positions(s.size()), encoded(s.size() + 1);
for (std::size_t i = 0; i < s.size(); ++i) positions[i] = static_cast<int>(i);
std::sort(positions.begin(), positions.end(), [&](int a, int b) { return s[a] < s[b]; });
int alphabet = 0;
for (std::size_t i = 0; i < positions.size(); ++i) {
if (i == 0 || s[positions[i - 1]] < s[positions[i]]) ++alphabet;
encoded[positions[i]] = alphabet;
}
if (alphabet == static_cast<int>(s.size())) return positions;
auto result = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_induced(std::span<const int>(encoded), alphabet);
result.erase(result.begin());
return result;
}
}
#endif
#ifndef SIRKIT_LCP_ARRAY_IMPL_DEFINED
#define SIRKIT_LCP_ARRAY_IMPL_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
template <class Sequence>
std::vector<int> suffix_lcp(const Sequence& s, const std::vector<int>& sa) {
/*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_length_check(s.size());
#ifndef SKIP_RUNTIME_CHECKS
if (sa.size() != s.size()) throw std::invalid_argument("lcp_array: size");
#endif
const int n = static_cast<int>(s.size());
if (n == 0) return {};
#ifndef SKIP_RUNTIME_CHECKS
std::vector<int> rank(s.size(), -1);
#else
// 妥当なsaの順列から全要素を設定してから参照する。
auto rank = std::make_unique_for_overwrite<int[]>(s.size());
#endif
for (int i = 0; i < n; ++i) {
#ifndef SKIP_RUNTIME_CHECKS
if (sa[i] < 0 || sa[i] >= n || rank[sa[i]] != -1)
throw std::invalid_argument("lcp_array: suffix permutation");
#endif
rank[sa[i]] = i;
}
if (n < 2) return {};
std::vector<int> lcp(static_cast<std::size_t>(n - 1));
int length = 0;
for (int i = 0; i < n; ++i) {
const int order = rank[i];
if (order + 1 == n) { length = 0; continue; }
const int j = sa[order + 1];
while (length < n - i && length < n - j && s[i + length] == s[j + length]) ++length;
lcp[order] = length;
if (length != 0) --length;
}
return lcp;
}
}
#endif
#ifndef SIRKIT_LCP_ARRAY_DEFINED
#define SIRKIT_LCP_ARRAY_DEFINED
template<class T>
std::vector<int> lcp_array(const std::vector<T>& s, const std::vector<int>& sa) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_lcp(s, sa);
}
inline std::vector<int> lcp_array(const std::string& s, const std::vector<int>& sa) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_lcp(s, sa);
}
template<class Sequence>
requires requires(const Sequence& s) { s.size(); s[0] == s[0]; }
std::vector<int> lcp_array(const Sequence& s, const std::vector<int>& sa) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_lcp(s, sa);
}
#endif
#ifndef SIRKIT_SUFFIX_ARRAY_EQUAL_RANGE_DEFINED
#define SIRKIT_SUFFIX_ARRAY_EQUAL_RANGE_DEFINED
inline std::pair<int, int> SuffixArrayEqualRange(std::string_view s, const std::vector<int>& sa,
std::string_view pattern) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_search(s, sa, pattern, [](char c) { return static_cast<unsigned char>(c); });
}
template <std::integral T>
std::pair<int, int> SuffixArrayEqualRange(const std::vector<T>& s, const std::vector<int>& sa,
const std::vector<T>& pattern) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::suffix_search(s, sa, pattern, [](T value) { return value; });
}
#endif
#ifndef SIRKIT_SUFFIX_TREE_DEFINED
#define SIRKIT_SUFFIX_TREE_DEFINED
namespace detail
{
inline void suffix_tree_length_check(std::size_t length)
{
constexpr auto kLimit = static_cast<std::size_t>((std::numeric_limits<int>::max() - 1) / 2);
if (length > kLimit)
{
throw std::length_error("SuffixTree: text too long");
}
}
} // namespace detail
class SuffixTree
{
public:
struct Node
{
int parent;
int depth;
int suffix_start;
int first_suffix;
int last_suffix;
};
struct Repeat
{
int first_start = 0;
int second_start = 0;
int length = 0;
};
explicit SuffixTree(std::string_view text) : data_(std::make_shared<const Data>(text))
{
}
SuffixTree(const SuffixTree &) noexcept = default;
SuffixTree &operator=(const SuffixTree &) noexcept = default;
[[nodiscard]] std::span<const Node> nodes() const noexcept
{
return data_->nodes;
}
[[nodiscard]] std::span<const int> children(int vertex) const
{
return data_->children_of(vertex_index(vertex));
}
[[nodiscard]] std::span<const int> suffixes(int vertex) const
{
const auto &node = data_->nodes[vertex_index(vertex)];
const auto first = static_cast<std::size_t>(node.first_suffix);
const auto count = static_cast<std::size_t>(node.last_suffix - node.first_suffix);
return std::span<const int>(data_->suffix_array_order).subspan(first, count);
}
[[nodiscard]] std::string_view edge_label(int vertex) const
{
const auto &node = data_->nodes[vertex_index(vertex)];
if (vertex == 0)
{
return {};
}
const int parent_depth = data_->nodes[node.parent].depth;
const int representative = data_->suffix_array_order[node.first_suffix];
return std::string_view(data_->text).substr(
static_cast<std::size_t>(representative + parent_depth),
static_cast<std::size_t>(node.depth - parent_depth));
}
[[nodiscard]] Repeat longest_nonoverlapping_repeat() const
{
const auto &data = *data_;
std::vector<std::size_t> order;
order.reserve(data.nodes.size());
order.push_back(0);
for (std::size_t i = 0; i < order.size(); ++i)
{
for (const int child : data.children_of(order[i]))
{
order.push_back(static_cast<std::size_t>(child));
}
}
std::vector<std::pair<int, int>> span(data.nodes.size());
Repeat best;
for (auto it = order.rbegin(); it != order.rend(); ++it)
{
const auto vertex = *it;
const auto &node = data.nodes[vertex];
int first = static_cast<int>(data.text.size());
int last = 0;
if (node.suffix_start >= 0)
{
first = last = node.suffix_start;
}
for (const int child : data.children_of(vertex))
{
first = std::min(first, span[child].first);
last = std::max(last, span[child].second);
}
span[vertex] = {first, last};
// 同じ接頭辞を持つうち、距離が最大の二つの出現を使う。
const int length = std::min(node.depth, last - first);
if (length > best.length)
{
best = {first, last, length};
}
}
return best;
}
private:
struct Data
{
explicit Data(std::string_view source)
{
detail::suffix_tree_length_check(source.size());
text.assign(source);
suffix_array_order = suffix_array(text);
const auto lcp = lcp_array(text, suffix_array_order);
const int length = static_cast<int>(text.size());
nodes.reserve(text.size() + 1);
nodes.push_back({-1, 0, -1, 0, length});
std::vector<int> open{0};
for (int rank = 0; rank < length; ++rank)
{
const int common = rank == 0 ? 0 : lcp[rank - 1];
int child = 0;
while (nodes[open.back()].depth > common)
{
child = open.back();
nodes[child].last_suffix = rank;
open.pop_back();
}
int parent = open.back();
if (nodes[parent].depth < common)
{
// 前の枝の途中で新しい接尾辞と分かれる。その位置に頂点を挿入する。
const int split = static_cast<int>(nodes.size());
nodes.push_back({parent, common, -1, nodes[child].first_suffix, length});
nodes[child].parent = split;
open.push_back(split);
parent = split;
}
const int endpoint = static_cast<int>(nodes.size());
const int start = suffix_array_order[rank];
nodes.push_back({parent, length - start, start, rank, length});
open.push_back(endpoint);
}
child_offsets.resize(nodes.size() + 1);
for (std::size_t i = 1; i < nodes.size(); ++i)
{
++child_offsets[static_cast<std::size_t>(nodes[i].parent) + 1];
}
std::partial_sum(child_offsets.begin(), child_offsets.end(), child_offsets.begin());
auto next = child_offsets;
edges.resize(nodes.size() - 1);
for (std::size_t i = 1; i < nodes.size(); ++i)
{
edges[next[nodes[i].parent]++] = static_cast<int>(i);
}
}
[[nodiscard]] std::span<const int> children_of(std::size_t vertex) const noexcept
{
const auto first = child_offsets[vertex];
const auto count = child_offsets[vertex + 1] - first;
return std::span<const int>(edges).subspan(first, count);
}
std::string text;
std::vector<int> suffix_array_order;
std::vector<Node> nodes;
std::vector<std::size_t> child_offsets;
std::vector<int> edges;
};
[[nodiscard]] std::size_t vertex_index(int vertex) const
{
#ifndef SKIP_RUNTIME_CHECKS
if (vertex < 0 || static_cast<std::size_t>(vertex) >= data_->nodes.size())
{
throw std::out_of_range("SuffixTree: vertex index");
}
#endif
return static_cast<std::size_t>(vertex);
}
std::shared_ptr<const Data> data_;
};
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1