競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
整数の多重集合を版ごとに保持します。接頭辞の版を順に作ると、添字区間内のk番目の値やXOR後の最小値を求められます。
sirkit::PersistentBinaryTrie<unsigned, 9> trie(3);
const auto a = trie.insert({}, 2);
const auto b = trie.insert(a, 5);
const auto c = trie.insert(b, 3);
trie.kth_xor(a, c, 0); // {5, 3} の最小値 3
trie.kth_xor(a, c, 0, 6); // {5 ^ 6, 3 ^ 6} の最小値 3
trie.size(a); // 1
PersistentBinaryTriePersistentBinaryTrie<T = std::uint32_t, MAX_LOG = std::numeric_limits<T>::digits - 1>
explicit PersistentBinaryTrie(std::size_t expected_updates = 0)
T は bool を除く符号なし整数型です。キーとXORマスクは B = MAX_LOG + 1 ビット以内です。既定では T の全ビットを使います。構築時は見込みの更新回数に応じて領域を確保します。
空の版は Version{} で表します。更新後の版は同じ木で使います。木を破棄したり、別の木を代入したりすると、それまでの版は使えなくなります。
insertVersion insert(Version version, T key)
key を1個加えた版を返します。元の版も使えます。償却 O(B) 時間、追加領域 O(B) です。
erasestd::optional<Version> erase(Version version, T key)
key を1個除いた版を返します。キーがなければ std::nullopt を返します。償却 O(B) 時間、追加領域 O(B) です。
size と countstd::uint32_t size(Version version) const
std::uint32_t count(Version version, T key) const
版の要素数を O(1)、指定キーの個数を O(B) で返します。
kth_xorstd::optional<T> kth_xor(Version before, Version after, std::uint32_t k, T mask = 0) const
after から before の要素を引いた多重集合で、key ^ mask の昇順で0始まりの k 番目の値を返します。要素が足りなければ std::nullopt です。before は after の部分多重集合である必要があります。時間は O(B) です。
count_xor_lessstd::uint32_t count_xor_less(Version before, Version after, T bound, T mask = 0) const
同じ差分で key ^ mask < bound を満たす要素数を O(B) で返します。bound がキーの最大値より大きければ差分の要素数を返します。
PersistentBinaryTrie<T,MAX_LOG>(expected_updates=0): 空の多重集合。更新回数の見込みに応じて容量を確保する。
Tはboolを除く符号なし整数。MAX_LOGは最高位ビット番号で既定値はTのビット数-1。B=MAX_LOG+1。
Version{}: 空集合の版。各版は作成した木で使う。キー・マスクはBビット以内。
size(version): 多重集合の要素数を返す。O(1)。count(version,key): キーの個数を返す。O(B)。
insert(version,key): キーを1個追加した版を返す。元の版は保持する。償却O(B)時間・追加O(B)領域。
erase(version,key): キーを1個除いた版を返す。存在しない場合nullopt。償却O(B)時間・追加O(B)領域。
kth_xor(before,after,k,mask=0): 差分中でkey^maskが0始まりk番目の値。なければnullopt。O(B)。
count_xor_less(before,after,bound,mask=0): 差分中でkey^mask<boundとなる要素数。O(B)。
beforeはafterの部分多重集合。insertで作った接頭辞の版を使えば添字区間を照会できる。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Range Kth Smallest(永続二分Trie) | persistent_binary_trie_range_kth.cpp | 未提出 | — |
| Set Xor-Min(永続二分Trie) | persistent_binary_trie_xor_min.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/persistent_binary_trie.md
//
// API一覧
// PersistentBinaryTrie<T,MAX_LOG>(expected_updates=0): 空の多重集合。更新回数の見込みに応じて容量を確保する。
// Tはboolを除く符号なし整数。MAX_LOGは最高位ビット番号で既定値はTのビット数-1。B=MAX_LOG+1。
// Version{}: 空集合の版。各版は作成した木で使う。キー・マスクはBビット以内。
// size(version): 多重集合の要素数を返す。O(1)。count(version,key): キーの個数を返す。O(B)。
// insert(version,key): キーを1個追加した版を返す。元の版は保持する。償却O(B)時間・追加O(B)領域。
// erase(version,key): キーを1個除いた版を返す。存在しない場合nullopt。償却O(B)時間・追加O(B)領域。
// kth_xor(before,after,k,mask=0): 差分中でkey^maskが0始まりk番目の値。なければnullopt。O(B)。
// count_xor_less(before,after,bound,mask=0): 差分中でkey^mask<boundとなる要素数。O(B)。
// beforeはafterの部分多重集合。insertで作った接頭辞の版を使えば添字区間を照会できる。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <array>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_PERSISTENT_BINARY_TRIE_DEFINED
#define SIRKIT_PERSISTENT_BINARY_TRIE_DEFINED
template <std::unsigned_integral T = std::uint32_t, int MAX_LOG = std::numeric_limits<T>::digits - 1>
requires(!std::same_as<T, bool> && MAX_LOG >= 0 && MAX_LOG < std::numeric_limits<T>::digits)
class PersistentBinaryTrie
{
using Index = std::uint32_t;
static constexpr std::size_t kPathNodes = MAX_LOG + 2;
public:
class Version
{
friend class PersistentBinaryTrie;
public:
Version() = default;
private:
explicit Version(Index root) : root_(root)
{
}
Index root_ = 0;
};
explicit PersistentBinaryTrie(std::size_t expected_updates = 0)
{
Prepare(expected_updates);
}
std::uint32_t size(Version version) const
{
CheckVersion(version);
return Get(version.root_).count;
}
std::uint32_t count(Version version, T key) const
{
CheckVersion(version);
CheckKey(key);
Index node = version.root_;
for (int bit = MAX_LOG; bit >= 0 && node != 0; --bit)
{
node = Get(node).children[Bit(key, bit)];
}
return Get(node).count;
}
Version insert(Version version, T key)
{
CheckVersion(version);
CheckKey(key);
Prepare(1);
return Version(Change<true>(version.root_, key, MAX_LOG));
}
std::optional<Version> erase(Version version, T key)
{
if (count(version, key) == 0)
{
return std::nullopt;
}
Prepare(1);
return Version(Change<false>(version.root_, key, MAX_LOG));
}
std::optional<T> kth_xor(Version before, Version after, std::uint32_t k, T mask = 0) const
{
CheckInterval(before, after);
CheckKey(mask);
if (k >= Difference(before.root_, after.root_))
{
return std::nullopt;
}
T result = 0;
Index left = before.root_;
Index right = after.root_;
for (int bit = MAX_LOG; bit >= 0; --bit)
{
const auto side = Bit(mask, bit);
const auto count_zero = Difference(Get(left).children[side], Get(right).children[side]);
std::size_t direction = side;
if (k >= count_zero)
{
k -= count_zero;
direction ^= 1;
result |= T{1} << bit;
}
left = Get(left).children[direction];
right = Get(right).children[direction];
}
return result;
}
std::uint32_t count_xor_less(Version before, Version after, T bound, T mask = 0) const
{
CheckInterval(before, after);
CheckKey(mask);
Index left = before.root_;
Index right = after.root_;
if (!Fits(bound))
{
return Difference(left, right);
}
std::uint32_t smaller = 0;
for (int bit = MAX_LOG; bit >= 0 && left != right; --bit)
{
const auto zero = Bit(mask, bit);
const auto allows_zero = Bit(bound, bit);
if (allows_zero)
{
smaller += Difference(Get(left).children[zero], Get(right).children[zero]);
}
const auto direction = zero ^ allows_zero;
left = Get(left).children[direction];
right = Get(right).children[direction];
}
return smaller;
}
private:
struct Node
{
std::array<Index, 2> children{};
Index count{};
};
static constexpr Node kEmpty{};
std::vector<Node> nodes_;
const Node &Get(Index id) const
{
return id == 0 ? kEmpty : nodes_[id - 1];
}
static std::size_t Bit(T key, int bit)
{
return (key >> bit) & T{1};
}
static bool Fits(T key)
{
return (key >> MAX_LOG) <= T{1};
}
void Prepare(std::size_t updates)
{
const auto limit = std::min<std::size_t>(std::numeric_limits<Index>::max(), nodes_.max_size());
if (updates > (limit - nodes_.size()) / kPathNodes)
{
throw std::length_error("PersistentBinaryTrie: too many nodes");
}
const auto need = nodes_.size() + updates * kPathNodes;
const auto capacity = nodes_.capacity();
if (need > capacity)
{
const auto growth = std::min(capacity / 2, limit - capacity);
nodes_.reserve(std::max(need, capacity + growth));
}
}
template <bool Add>
Index Change(Index id, T key, int bit)
{
Node copy = Get(id);
if constexpr (Add)
{
++copy.count;
}
else
{
if (--copy.count == 0)
{
return 0;
}
}
if (bit >= 0)
{
const auto side = Bit(key, bit);
copy.children[side] = Change<Add>(copy.children[side], key, bit - 1);
}
nodes_.push_back(copy);
return static_cast<Index>(nodes_.size());
}
std::uint32_t Difference(Index before, Index after) const
{
return Get(after).count - Get(before).count;
}
void CheckVersion([[maybe_unused]] Version version) const
{
#ifndef SKIP_RUNTIME_CHECKS
if (version.root_ > nodes_.size())
{
throw std::out_of_range("PersistentBinaryTrie: invalid version");
}
#endif
}
static void CheckKey([[maybe_unused]] T key)
{
#ifndef SKIP_RUNTIME_CHECKS
if (!Fits(key))
{
throw std::out_of_range("PersistentBinaryTrie: key exceeds MAX_LOG");
}
#endif
}
void CheckInterval([[maybe_unused]] Version before, [[maybe_unused]] Version after) const
{
#ifndef SKIP_RUNTIME_CHECKS
if (size(before) > size(after))
{
throw std::invalid_argument("PersistentBinaryTrie: before has more elements than after");
}
#endif
}
};
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1