競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
Trieは文字列の重複個数、接頭辞、辞書順の照会を扱います。空文字列とNULを含む全256バイトに対応し、辞書順は符号なしバイトの順です。
以下、Lは入力語長、Kは返す語長、Nは保持ノード枠数、Tは保持索引枠数です。
TrieTrie();
Trie(const Trie&);
Trie(Trie&& other) noexcept;
引数を省略すると空のTrieを作ります。コピーしたTrieは元のTrieから独立し、ムーブでは所有権を移します。
制約: 追加の制約はありません。
計算量: 空・moveはO(1)、コピーはO(N+256T)。
operator=Trie& operator=(const Trie& other);
Trie& operator=(Trie&& other) noexcept;
独立コピー/所有権移動で代入し、自身への参照を返します。
制約: 同じ型の個体。
計算量: コピーは新旧の保持量に比例、move代入は旧状態の解放も含みます。
insertstd::size_t insert(std::string_view word, std::size_t copies = 1);
copies個追加してその語の個数を返します。copies=0なら照会のみ。
制約: 長さ付きバイト列を渡します。空語・NUL・全256バイトを扱います。
計算量: 償却O(16L+256)、再確保時は保持ノード・索引枠のコピーも加算。
erasebool erase(std::string_view word, std::size_t copies = 1) noexcept;
指定個数を削除できればtrueを返します。個数が足りなければ何も変更せずfalseを返し、指定個数が0ならtrueを返します。
制約: 長さ付きバイト列を渡します。空語・NUL・全256バイトを扱います。
計算量: O(16L+256)。
erase_allstd::size_t erase_all(std::string_view word) noexcept;
その語を全て削除し、削除した個数を返します。
制約: 長さ付きバイト列を渡します。空語・NUL・全256バイトを扱います。
計算量: O(16L+256)。
countstd::size_t count(std::string_view word) const noexcept;
その語の個数を返します。
制約: 長さ付きバイト列を渡します。空語・NUL・全256バイトを扱います。
計算量: 語長LにO(16L+1)。
containsbool contains(std::string_view word) const noexcept;
その語が1個以上あればtrueです。
制約: 長さ付きバイト列を渡します。空語・NUL・全256バイトを扱います。
計算量: 語長LにO(16L+1)。
prefix_countstd::size_t prefix_count(std::string_view prefix) const noexcept;
接頭辞を持つ語の総個数を返します。
制約: 長さ付きバイト列を渡します。空語・NUL・全256バイトを扱います。
計算量: 語長LにO(16L+1)。
starts_withbool starts_with(std::string_view prefix) const noexcept;
接頭辞を持つ語が存在すればtrueです。
制約: 長さ付きバイト列を渡します。空語・NUL・全256バイトを扱います。
計算量: 語長LにO(16L+1)。
longest_prefixstd::optional<std::size_t> longest_prefix(std::string_view text) const noexcept;
textの接頭辞に当たる登録語のうち、最長のものの長さを返します。該当する登録語がなければnulloptです。
制約: 長さ付きバイト列を渡します。空語・NUL・全256バイトを扱います。
計算量: 語長LにO(16L+1)。
語長Lに対し通常の検索はO(16L)、登録は償却O(16L+256)、削除はO(16L+256)です。登録の再確保には保持ノード枠・索引枠のコピーも加わります。個数不足の削除はfalseで内容不変です。
count_lessstd::size_t count_less(std::string_view word) const noexcept;
word未満の語の総個数を重複込みで返します。
制約: 符号なしバイトの辞書順を使います。
計算量: O(256L)。
kthstd::optional<std::string> kth(std::size_t k) const;
重複込み・0始まりk番目の語を返し、範囲外ならnulloptです。
制約: 追加の制約はありません。
計算量: 返す語の長さKにO(256K+1)。
lower_boundstd::optional<std::string> lower_bound(std::string_view word) const;
word以上の最小登録語を返し、なければnulloptです。
制約: 符号なしバイトの辞書順を使います。
計算量: O(256L+K)、空wordではO(K+1)。
itemsstd::vector<std::pair<std::string, std::size_t>> items( std::string_view prefix = {}, std::size_t limit = std::numeric_limits<std::size_t>::max()) const;
異なる語と個数を辞書順に最大limit件返します。
制約: prefixは長さ付きバイト列。
計算量: 接頭辞探索+訪問ノード数+返却文字列総長。
Kは返す語の長さです。空のlower_boundはO(K)です。
sizestd::size_t size() const noexcept;
重複込みの総個数を返します。
制約: 追加の制約はありません。
計算量: O(1)。
distinct_sizestd::size_t distinct_size() const noexcept;
異なる語数を返します。
制約: 追加の制約はありません。
計算量: O(1)。
emptybool empty() const noexcept;
空ならtrueです。
制約: 追加の制約はありません。
計算量: O(1)。
node_countstd::size_t node_count() const noexcept;
根を含む使用ノード数を返します。
制約: 追加の制約はありません。
計算量: O(1)。
capacitystd::size_t capacity() const noexcept;
確保済みノード枠数を返します。
制約: 追加の制約はありません。
計算量: O(1)。
clearvoid clear() noexcept;
全削除し、確保枠を保持します。
制約: 追加の制約はありません。
計算量: O(N+T)。
reserve_nodesvoid reserve_nodes(std::size_t n);
少なくともnノード分の枠を予約します。
制約: ノード容量の上限以下。
計算量: 最悪O(N)。
swapvoid swap(Trie& other) noexcept;
void swap(Trie& a, Trie& b) noexcept;
内容と確保枠を交換します。
制約: 追加の制約はありません。
計算量: O(1)。
TrieNode::TrieNodeTrieNode();
explicit TrieNode(std::unordered_map<char, std::shared_ptr<TrieNode>> values);
TrieNode(const TrieNode&);
TrieNode(TrieNode&&) noexcept;
既定/子map/子の所有権を共有するコピー/所有権移動で構築します。
制約: 別対象を所有するaliasingポインタ・循環所有は対象外。
計算量: 子mapのコピーに比例。既定とmoveはO(1)。
TrieNode::operator=TrieNode& operator=(const TrieNode&);
TrieNode& operator=(TrieNode&&) noexcept;
子mapをコピー/移動して代入します。
制約: 別対象を所有するaliasingポインタ・循環所有は対象外。
計算量: 子mapのコピーや旧所有状態の解放に比例。
保持ノード枠数N・索引枠数Tとして、コピーはO(N+256T)、破棄・clearはO(N+T)、reserve_nodesは最悪O(N)、swapはO(1)です。保持領域はO(N+256T)。コピーは独立し、移動元は空で再利用できます。
登録・コピー代入の確保失敗では論理的内容を保持しますが、容量は増える場合があります。個数と容量の上限保護はSKIP_RUNTIME_CHECKSでも残ります。
別の公開型TrieNodeは、既定構築または子mapから構築でき、childrenのコピーは子の所有権を共有します。別対象を所有するaliasingポインタ・循環所有は対象外です。深い木の破棄も反復処理です。
[TrieNode] TrieNode(): 空で生成。TrieNode(children): 子mapを受け取り、コピーは子を共有する。 children: 指すノード自体を所有する子(別対象の所有を借りるaliasingは対象外)。 破棄は反復処理。循環所有は解消しない。指定初期化は不可。 [Trie] 全バイトを扱う多重集合。辞書順は符号なしバイト順、空文字列も登録可。 Trie(): 空で生成。コピーは独立、move元は空で再利用可。 insert(word, copies=1): copies個追加し、その語の個数を返す。0なら照会のみ。 erase(word, copies=1): copies個だけ削除。個数不足ならfalseで不変、0ならtrue。 erase_all(word): その語を全削除し、削除した個数を返す。 count(word)/contains(word): その語の個数/存在を返す。 prefix_count(prefix)/starts_with(prefix): 接頭辞を持つ語の総個数/存在を返す。 size()/distinct_size()/empty(): 総個数/異なる語数/空かを返す。 node_count()/capacity(): rootを含む使用ノード数/確保済みノード枠を返す。 longest_prefix(text): 登録語のうちtextの最長接頭辞長。該当なしはnullopt。 count_less(word): word未満の語の総個数を返す(重複込み)。 kth(k): 0始まりのk番目の語。重複込み、範囲外はnullopt。 lower_bound(word): word以上の最小登録語。該当なしはnullopt。 items(prefix="", limit=SIZE_MAX): prefixを持つ異なる語と個数を辞書順に最大limit件返す。 clear(): 全削除し、確保枠を保持。reserve_nodes(n): 少なくともn枠を確保。 swap(other): 内容と確保枠を定数時間で交換。 count/contains/prefix系/longest_prefixは長さLに対しO(16L)、size系はO(1)。 insertは償却O(16L+256)、再確保時は保持ノード/索引枠数ぶんのコピーも発生。 erase/erase_allはO(16L+256)。count_less/kthは語長L/戻す長さKに対しO(256L)/O(256K)。 lower_boundはO(256L+K)。itemsは接頭辞探索+訪問ノード数+返す文字列総長。 保持ノード数N・保持索引数TとしてコピーはO(N+256T)、破棄・clearはO(N+T)。 reserve_nodesは最悪O(N)。使用メモリはノード枠数+256×索引枠数に比例。 個数・ノード枠の上限超過は検査省略時もlength_error。確保失敗はbad_alloc。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| 文字列検索(Trie) | preferred_trie_dictionary.cpp | 未提出 | — |
| C - gacha | trie_dictionary.cpp | 参考検証・移行先あり | AC |
| Trie 順序統計・削除の独立ローカル検査 | trie_local.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/trie.md
//
// API一覧
// [TrieNode]
// TrieNode(): 空で生成。TrieNode(children): 子mapを受け取り、コピーは子を共有する。
// children: 指すノード自体を所有する子(別対象の所有を借りるaliasingは対象外)。
// 破棄は反復処理。循環所有は解消しない。指定初期化は不可。
//
// [Trie]
// 全バイトを扱う多重集合。辞書順は符号なしバイト順、空文字列も登録可。
// Trie(): 空で生成。コピーは独立、move元は空で再利用可。
// insert(word, copies=1): copies個追加し、その語の個数を返す。0なら照会のみ。
// erase(word, copies=1): copies個だけ削除。個数不足ならfalseで不変、0ならtrue。
// erase_all(word): その語を全削除し、削除した個数を返す。
// count(word)/contains(word): その語の個数/存在を返す。
// prefix_count(prefix)/starts_with(prefix): 接頭辞を持つ語の総個数/存在を返す。
// size()/distinct_size()/empty(): 総個数/異なる語数/空かを返す。
// node_count()/capacity(): rootを含む使用ノード数/確保済みノード枠を返す。
// longest_prefix(text): 登録語のうちtextの最長接頭辞長。該当なしはnullopt。
// count_less(word): word未満の語の総個数を返す(重複込み)。
// kth(k): 0始まりのk番目の語。重複込み、範囲外はnullopt。
// lower_bound(word): word以上の最小登録語。該当なしはnullopt。
// items(prefix="", limit=SIZE_MAX): prefixを持つ異なる語と個数を辞書順に最大limit件返す。
// clear(): 全削除し、確保枠を保持。reserve_nodes(n): 少なくともn枠を確保。
// swap(other): 内容と確保枠を定数時間で交換。
// count/contains/prefix系/longest_prefixは長さLに対しO(16L)、size系はO(1)。
// insertは償却O(16L+256)、再確保時は保持ノード/索引枠数ぶんのコピーも発生。
// erase/erase_allはO(16L+256)。count_less/kthは語長L/戻す長さKに対しO(256L)/O(256K)。
// lower_boundはO(256L+K)。itemsは接頭辞探索+訪問ノード数+返す文字列総長。
// 保持ノード数N・保持索引数TとしてコピーはO(N+256T)、破棄・clearはO(N+T)。
// reserve_nodesは最悪O(N)。使用メモリはノード枠数+256×索引枠数に比例。
// 個数・ノード枠の上限超過は検査省略時もlength_error。確保失敗はbad_alloc。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_TRIE_NODE_DEFINED
#define SIRKIT_TRIE_NODE_DEFINED
struct TrieNode {
std::unordered_map<char, std::shared_ptr<TrieNode>> children;
TrieNode() = default;
explicit TrieNode(std::unordered_map<char, std::shared_ptr<TrieNode>> values)
: children(std::move(values)) {}
TrieNode(const TrieNode&) = default;
TrieNode(TrieNode&&) noexcept = default;
TrieNode& operator=(const TrieNode&) = default;
TrieNode& operator=(TrieNode&&) noexcept = default;
~TrieNode() {
std::shared_ptr<TrieNode> pending;
detach_children(*this, pending);
while (pending) {
auto current = std::move(pending);
pending = std::move(current->pending_);
detach_children(*current, pending);
}
}
private:
std::shared_ptr<TrieNode> pending_;
static void detach_children(TrieNode& node, std::shared_ptr<TrieNode>& pending) noexcept {
while (!node.children.empty()) {
auto it = node.children.begin();
auto child = std::move(it->second);
node.children.erase(it);
if (child && child.use_count() == 1) {
child->pending_ = std::move(pending);
pending = std::move(child);
}
}
}
};
#endif
#ifndef SIRKIT_TRIE_DEFINED
#define SIRKIT_TRIE_DEFINED
namespace detail {
inline void CheckTrieCapacity(std::size_t count, std::size_t limit, const char* message) {
if (count > limit) throw std::length_error(message);
}
}
// 子はソート済み兄弟リスト。次数16で256要素の索引を追加、8未満で回収。
// 破棄・clear・列挙は再帰しない。64文字までの追加経路は固定長の作業配列へ記録。
class Trie {
static constexpr std::size_t none = std::numeric_limits<std::size_t>::max();
static constexpr std::uint32_t no_table = std::numeric_limits<std::uint32_t>::max();
static constexpr std::uint16_t index_threshold = 16;
struct Node {
std::size_t subtree = 0;
std::size_t terminal = 0;
std::size_t first_child = none;
std::size_t next_sibling = none;
unsigned char byte = 0;
std::uint16_t degree = 0;
std::uint32_t table = no_table;
};
struct Table {
std::array<std::size_t, 256> entries;
Table() noexcept { entries.fill(none); }
};
std::vector<Node> nodes_{1};
std::vector<Table> tables_;
std::uint32_t free_table_ = no_table;
std::size_t free_head_ = none;
std::size_t live_ = 1;
std::size_t distinct_ = 0;
std::size_t child(std::size_t parent, unsigned char byte) const noexcept {
if (nodes_[parent].table != no_table)
return tables_[nodes_[parent].table].entries[byte];
std::size_t p = nodes_[parent].first_child;
while (p != none && nodes_[p].byte < byte) p = nodes_[p].next_sibling;
return p != none && nodes_[p].byte == byte ? p : none;
}
std::size_t find(std::string_view word) const noexcept {
if (nodes_.empty()) return none;
std::size_t p = 0;
for (char value : word) {
const unsigned char byte = static_cast<unsigned char>(value);
p = child(p, byte);
if (p == none) return none;
}
return p;
}
void release_table(std::size_t p) noexcept {
if (nodes_[p].table == no_table) return;
tables_[nodes_[p].table].entries[0] = free_table_;
free_table_ = nodes_[p].table;
nodes_[p].table = no_table;
}
std::size_t allocate_node(unsigned char byte, std::size_t& fresh) noexcept {
std::size_t p;
if (free_head_ != none) {
p = free_head_;
free_head_ = nodes_[p].first_child;
nodes_[p] = Node{};
} else {
p = fresh++;
}
nodes_[p].byte = byte;
++live_;
return p;
}
void remove_known(std::string_view word, std::size_t copies) noexcept {
nodes_[0].subtree -= copies;
std::size_t parent = 0;
for (char value : word) {
const unsigned char byte = static_cast<unsigned char>(value);
std::size_t p = child(parent, byte);
nodes_[p].subtree -= copies;
if (nodes_[p].subtree == 0) {
std::size_t* link = &nodes_[parent].first_child;
while (*link != p) link = &nodes_[*link].next_sibling;
*link = nodes_[p].next_sibling;
if (nodes_[parent].table != no_table)
tables_[nodes_[parent].table].entries[byte] = none;
if (--nodes_[parent].degree < index_threshold / 2) release_table(parent);
// 消えた語だけからなる単一路を空きリストへ戻す。
while (p != none) {
const std::size_t next = nodes_[p].first_child;
release_table(p);
nodes_[p].first_child = free_head_;
free_head_ = p;
--live_;
p = next;
}
--distinct_;
return;
}
parent = p;
}
nodes_[parent].terminal -= copies;
if (nodes_[parent].terminal == 0) --distinct_;
}
std::optional<std::string> lower_bound_nonempty(std::string_view word) const {
if (empty()) return std::nullopt;
// 一致経路の最も深い位置で、次に大きい兄弟を候補として保持する。
std::size_t p = 0, alternative = none, prefix_length = 0, i = 0;
for (; i < word.size(); ++i) {
const auto byte = static_cast<unsigned char>(word[i]);
std::size_t next = nodes_[p].first_child;
while (next != none && nodes_[next].byte < byte)
next = nodes_[next].next_sibling;
if (next == none) break;
if (nodes_[next].byte != byte) {
alternative = next; prefix_length = i;
break;
}
if (nodes_[next].next_sibling != none) {
alternative = nodes_[next].next_sibling; prefix_length = i;
}
p = next;
}
std::string answer;
if (i == word.size()) {
answer.assign(word);
} else {
if (alternative == none) return std::nullopt;
answer.assign(word.substr(0, prefix_length));
p = alternative;
answer.push_back(static_cast<char>(nodes_[p].byte));
}
while (nodes_[p].terminal == 0) {
p = nodes_[p].first_child;
answer.push_back(static_cast<char>(nodes_[p].byte));
}
return answer;
}
public:
Trie() = default;
Trie(const Trie&) = default;
Trie& operator=(const Trie& other) {
if (this != &other) {
Trie copied(other);
swap(copied);
}
return *this;
}
Trie(Trie&& other) noexcept : nodes_(std::move(other.nodes_)),
tables_(std::move(other.tables_)), free_table_(std::exchange(other.free_table_, no_table)),
free_head_(std::exchange(other.free_head_, none)),
live_(std::exchange(other.live_, 1)), distinct_(std::exchange(other.distinct_, 0)) {
other.nodes_.clear();
other.tables_.clear();
}
Trie& operator=(Trie&& other) noexcept {
if (this != &other) {
nodes_ = std::move(other.nodes_);
tables_ = std::move(other.tables_);
free_table_ = std::exchange(other.free_table_, no_table);
free_head_ = std::exchange(other.free_head_, none);
live_ = std::exchange(other.live_, 1);
distinct_ = std::exchange(other.distinct_, 0);
other.nodes_.clear();
other.tables_.clear();
}
return *this;
}
std::size_t insert(std::string_view word, std::size_t copies = 1) {
if (copies == 0) return count(word);
if (copies > none - size()) throw std::length_error("Trie: count overflow");
std::array<std::size_t, 64> path;
std::size_t matched = 0, p = 0;
if (!nodes_.empty()) {
while (matched < word.size()) {
const std::size_t next = child(p, static_cast<unsigned char>(word[matched]));
if (next == none) break;
p = next;
if (matched < path.size()) path[matched] = p;
++matched;
}
}
const std::size_t needed = word.size() - matched;
detail::CheckTrieCapacity(needed, nodes_.max_size() - live_, "Trie: node capacity overflow");
const std::size_t old_size = nodes_.size();
const std::size_t free_count = old_size == 0 ? 0 : old_size - live_;
const std::size_t additional = needed > free_count ? needed - free_count : 0;
const std::size_t root_needed = old_size == 0 ? 1 : 0;
const std::size_t branch = p;
const bool needs_index = needed != 0 && old_size != 0 &&
nodes_[branch].table == no_table && nodes_[branch].degree + 1 >= index_threshold;
bool appended_table = false;
// 全確保を先に済ませ、例外時に内容を変えない。
if (needs_index && free_table_ == no_table) {
detail::CheckTrieCapacity(tables_.size(), no_table - 1, "Trie: index capacity overflow");
tables_.emplace_back();
appended_table = true;
}
try {
nodes_.resize(old_size + root_needed + additional);
} catch (...) {
if (appended_table) tables_.pop_back();
throw;
}
if (needs_index) {
std::uint32_t table;
if (appended_table) {
table = static_cast<std::uint32_t>(tables_.size() - 1);
} else {
table = free_table_;
free_table_ = static_cast<std::uint32_t>(tables_[table].entries[0]);
tables_[table].entries.fill(none);
}
nodes_[branch].table = table;
for (std::size_t c = nodes_[branch].first_child; c != none; c = nodes_[c].next_sibling)
tables_[table].entries[nodes_[c].byte] = c;
}
std::size_t fresh = old_size + root_needed;
p = 0;
nodes_[0].subtree += copies;
for (std::size_t i = 0; i < matched; ++i) {
p = i < path.size() ? path[i] : child(p, static_cast<unsigned char>(word[i]));
nodes_[p].subtree += copies;
}
// 新規ノードだけの末尾は単一路としてまとめて接続する。
if (needed != 0 && free_head_ == none) {
const std::size_t first = fresh;
for (std::size_t i = matched; i < word.size(); ++i) {
auto& node = nodes_[fresh++];
node.byte = static_cast<unsigned char>(word[i]);
node.subtree = copies;
if (i + 1 != word.size()) {
node.first_child = fresh;
node.degree = 1;
}
}
const unsigned char byte = static_cast<unsigned char>(word[matched]);
std::size_t* link = &nodes_[p].first_child;
while (*link != none && nodes_[*link].byte < byte)
link = &nodes_[*link].next_sibling;
nodes_[first].next_sibling = *link;
*link = first;
++nodes_[p].degree;
if (nodes_[p].table != no_table) tables_[nodes_[p].table].entries[byte] = first;
live_ += needed;
p = fresh - 1;
} else for (std::size_t i = matched; i < word.size(); ++i) {
const unsigned char byte = static_cast<unsigned char>(word[i]);
const std::size_t next = allocate_node(byte, fresh);
nodes_[next].subtree = copies;
std::size_t* link = &nodes_[p].first_child;
while (*link != none && nodes_[*link].byte < byte)
link = &nodes_[*link].next_sibling;
nodes_[next].next_sibling = *link;
*link = next;
++nodes_[p].degree;
if (nodes_[p].table != no_table) tables_[nodes_[p].table].entries[byte] = next;
p = next;
}
if (nodes_[p].terminal == 0) ++distinct_;
return nodes_[p].terminal += copies;
}
bool erase(std::string_view word, std::size_t copies = 1) noexcept {
if (copies == 0) return true;
if (count(word) < copies) return false;
remove_known(word, copies);
return true;
}
std::size_t erase_all(std::string_view word) noexcept {
const std::size_t copies = count(word);
if (copies != 0) remove_known(word, copies);
return copies;
}
std::size_t count(std::string_view word) const noexcept {
const std::size_t p = find(word);
return p == none ? 0 : nodes_[p].terminal;
}
bool contains(std::string_view word) const noexcept { return count(word) != 0; }
std::size_t prefix_count(std::string_view prefix) const noexcept {
const std::size_t p = find(prefix);
return p == none ? 0 : nodes_[p].subtree;
}
bool starts_with(std::string_view prefix) const noexcept { return prefix_count(prefix) != 0; }
std::size_t size() const noexcept { return nodes_.empty() ? 0 : nodes_[0].subtree; }
std::size_t distinct_size() const noexcept { return distinct_; }
bool empty() const noexcept { return size() == 0; }
std::size_t node_count() const noexcept { return live_; }
std::size_t capacity() const noexcept { return nodes_.capacity(); }
std::optional<std::size_t> longest_prefix(std::string_view text) const noexcept {
if (nodes_.empty()) return std::nullopt;
std::optional<std::size_t> result;
std::size_t p = 0;
if (nodes_[0].terminal != 0) result = 0;
for (std::size_t i = 0; i < text.size(); ++i) {
p = child(p, static_cast<unsigned char>(text[i]));
if (p == none) break;
if (nodes_[p].terminal != 0) result = i + 1;
}
return result;
}
std::size_t count_less(std::string_view word) const noexcept {
if (nodes_.empty()) return 0;
std::size_t answer = 0, p = 0;
for (char value : word) {
const unsigned char byte = static_cast<unsigned char>(value);
answer += nodes_[p].terminal;
std::size_t next = nodes_[p].first_child;
while (next != none && nodes_[next].byte < byte) {
answer += nodes_[next].subtree;
next = nodes_[next].next_sibling;
}
if (next == none || nodes_[next].byte != byte) return answer;
p = next;
}
return answer;
}
std::optional<std::string> kth(std::size_t k) const {
if (k >= size()) return std::nullopt;
std::string answer;
std::size_t p = 0;
for (;;) {
if (k < nodes_[p].terminal) return answer;
k -= nodes_[p].terminal;
p = nodes_[p].first_child;
while (k >= nodes_[p].subtree) {
k -= nodes_[p].subtree;
p = nodes_[p].next_sibling;
}
answer.push_back(static_cast<char>(nodes_[p].byte));
}
}
std::optional<std::string> lower_bound(std::string_view word) const {
return word.empty() ? kth(0) : lower_bound_nonempty(word);
}
std::vector<std::pair<std::string, std::size_t>> items(
std::string_view prefix = {}, std::size_t limit = none) const {
std::vector<std::pair<std::string, std::size_t>> result;
if (limit == 0) return result;
const std::size_t p = find(prefix);
if (p == none || nodes_[p].subtree == 0) return result;
std::string word(prefix);
if (nodes_[p].terminal != 0) {
result.emplace_back(word, nodes_[p].terminal);
if (result.size() == limit) return result;
}
std::vector<std::size_t> pending{nodes_[p].first_child};
while (!pending.empty()) {
const std::size_t next = pending.back();
if (next == none) {
pending.pop_back();
if (!pending.empty()) word.pop_back();
continue;
}
pending.back() = nodes_[next].next_sibling;
word.push_back(static_cast<char>(nodes_[next].byte));
if (nodes_[next].terminal != 0) {
result.emplace_back(word, nodes_[next].terminal);
if (result.size() == limit) return result;
}
pending.push_back(nodes_[next].first_child);
}
return result;
}
void clear() noexcept {
if (!nodes_.empty()) {
nodes_.resize(1);
nodes_[0] = Node{};
}
tables_.clear();
free_table_ = no_table;
free_head_ = none;
live_ = 1;
distinct_ = 0;
}
void reserve_nodes(std::size_t n) { nodes_.reserve(n); }
void swap(Trie& other) noexcept {
nodes_.swap(other.nodes_);
tables_.swap(other.tables_);
std::swap(free_table_, other.free_table_);
std::swap(free_head_, other.free_head_);
std::swap(live_, other.live_);
std::swap(distinct_, other.distinct_);
}
friend void swap(Trie& a, Trie& b) noexcept { a.swap(b); }
};
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1