sirkit-cpp-library

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

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

永続セグメント木

DataStructure/Persistent_Segment_Tree.cpp · ソース · 文書 Last Commit

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

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

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

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

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

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

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

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

PersistentSegmentTree<T,Op>は、過去の列を残したまま点を更新します。各版をRootで指定し、古い版から分岐した更新もできます。区間は0始まりの半開区間[l,r)で、集約は左から右の順序を保ちます。使用例を参照してください。

以下、Nは要素数です。値の演算・コピーをO(1)として計算量を記します。

コンストラクタ

PersistentSegmentTree(std::size_t n, Op op, T identity);
PersistentSegmentTree(std::span<const T> values, Op op, T identity);
PersistentSegmentTree(const std::vector<T>& values, Op op, T identity);
PersistentSegmentTree(const PersistentSegmentTree& other);
PersistentSegmentTree(PersistentSegmentTree&&) noexcept = default;

長さnの全要素を単位元で初期化するか、指定したvectorまたはspanから初期版を構築します。

制約: 冒頭の値型・演算の前提を満たすこと。指定する列長は内部容量の上限内です。

計算量: 長さ指定はO(1)。密な列の構築はO(N+1)時間・領域。 コピーはallocated_nodes()に比例、ムーブ構築はO(1)。

empty_root

Root empty_root() const;

全要素がidentityの版を表すRootを返します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: O(1)。

latest_root

Root latest_root() const;

最後に構築・更新したRootを返します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: O(1)。

build

Root build(std::span<const T> values);
Root build(const std::vector<T>& values);

同じ長さの指定列から新しい版を構築し、Rootを返します。

制約: 入力の長さはsize()と同じ。

計算量: O(N+1)時間・追加領域。N>0で2N-1ノードを追加。

set

Root set(const Root& root, std::size_t position, const T& replacement);

指定版の一点を置き換えた新しいRootを返します。元の版は変更しません。

制約: Rootは現在の所有者に属し、有効期間内であること。0<=position<size()。

計算量: O(log(N+1))時間・追加領域。

transform

template<class F> Root transform(const Root& root, std::size_t position, F function);

指定版の一点へ関数を適用した新しいRootを返します。元の版を変更しません。

制約: Rootは現在の所有者に属し、有効期間内であること。0<=position<size()。

計算量: O(log(N+1))時間・追加領域。

get

T get(const Root& root, std::size_t position) const;

指定版の一点のTを返します。

制約: Rootは現在の所有者に属し、有効期間内であること。0<=position<size()。

計算量: O(log(N+1))。

prod

T prod(const Root& root, std::size_t left, std::size_t right) const;

指定版の半開区間を左から集約したTを返します。空区間はidentityです。

制約: 有効なRootと0<=left<=right<=size()を渡すこと。

計算量: O(log(N+1))。

all_prod

T all_prod(const Root& root) const;

指定版の全体の集約値を返します。空列はidentityです。

制約: 現在の所有者に属する有効なRootを渡すこと。

計算量: O(1)。

max_right

template<class Pred> std::size_t max_right(const Root& root, std::size_t left, Pred pred) const;

左端lを固定し、述語を満たす最大の右端を返します。

制約: 有効なRootと範囲内の端点を渡し、pred(identity)=trueかつ述語が区間の伸長に対し単調であること。

計算量: O(log(N+1))。

min_left

template<class Pred> std::size_t min_left(const Root& root, std::size_t right, Pred pred) const;

右端rを固定し、述語を満たす最小の左端を返します。

制約: 有効なRootと範囲内の端点を渡し、pred(identity)=trueかつ述語が区間の伸長に対し単調であること。

計算量: O(log(N+1))。

size

std::size_t size() const noexcept;

要素数を返します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: O(1)。

empty

bool empty() const noexcept;

空ならtrueを返します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: O(1)。

allocated_nodes

std::size_t allocated_nodes() const noexcept;

現在確保しているノード数を返します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: O(1)。

reserve

void reserve(std::size_t nodes);

追加ノードを含めて指定数まで確保できる領域を予約します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: 再確保時はallocated_nodes()に比例。予約済みならO(1)。

reset

void reset(std::size_t n);

列長を変更して既存ノード・版を破棄します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: 旧ノード数に比例する時間。

clear

void clear();

列長を0にし、既存ノード・版を破棄します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: 旧ノード数に比例する時間。

remap_from

Root remap_from(const PersistentSegmentTree& original, const Root& root) const;

コピー元のRootを、コピー先の木で同じ版を表すRootへ変換します。

制約: originalからコピーした表で、そのコピー元の有効なRootを渡すこと。

計算量: O(1)。

PersistentSegmentTree<std::int64_t,std::plus<std::int64_t>> tree(
    std::vector<std::int64_t>{2,4,1},{},0);
auto first = tree.latest_root();
auto second = tree.set(first,1,9);
auto third = tree.transform(first,2,[](auto x){return x+5;});
// all_prod(first)==7、all_prod(second)==12、prod(third,1,3)==10。

Rootと所有権

Rootは小さな不変の値で、作成した木へ渡します。木の破棄・reset・clear後には使えません。コピー先で元のRootを直接使うこともできません。copy.remap_from(original,root)で変換できるのは、直接のコピー元にコピー時点で存在したRootだけです。コピーしたノード列は独立し、以後の更新は互いに影響しません。

moveでは既存Rootが移動先へ所属し、move元には破棄・代入だけを行います。swapはRootの所属も交換します。更新・構築で確保や演算・コピーが失敗した場合、追加ノードを取り消し、古い版とlatest_rootを保持します。コピー代入には強い例外保証があります。演算の外部状態は巻き戻さず、コールバックから同じ木を再入して変更しないでください。

前提と計算量

Opはconst呼出可能な結合演算、identityは左右の単位元です。T・Opはコピー可能、Tの破棄は例外を投げない型を使います。演算・コピーをO(1)として、点更新はO(log(N+1))時間・追加領域、点取得・区間積・境界探索はO(log(N+1))です。密な構築はN>0で2N-1ノード、点更新は高々1+ceil(log2(N))ノードを追加します。

境界探索の述語はpred(identity)がtrueで、区間を伸ばしてfalseになった後はtrueへ戻らないことが前提です。長さ0では空のRootだけを作れ、空区間積・全体積はidentityです。reset・clearには旧ノード数に比例する破棄費用がかかります。

根の所属・添字・区間・長さは既定で検査します。SKIP_RUNTIME_CHECKSは入力検査と所属確認用の状態を除きますが、Rootの所属と有効期間は利用側で守る必要があります。ノード数の内部上限は常に維持します。

数学的参考はAAL、機能上の参考はNyaanです。実装は整数添字で所有するノード列として組み直しています。

swap

void swap(PersistentSegmentTree& other) noexcept;
friend void swap(PersistentSegmentTree& a, PersistentSegmentTree& b) noexcept;

内容とRootの所属を交換します。

制約: Rootの所有者と有効期間の共通条件を満たすこと。

計算量: O(1)。値型・比較器のswapの費用は別です。

operator=

PersistentSegmentTree& operator=(const PersistentSegmentTree& other);
PersistentSegmentTree& operator=(PersistentSegmentTree&&) noexcept = default;

コピーまたはムーブで内容を置き換え、自身への参照を返します。コピーは独立した内容を持ちます。

制約: 型・所有・例外保証は共通の説明に従います。

計算量: 保持する配列・ノードのコピーと旧内容の破棄に比例。ムーブ構築とは異なり、代入では旧内容の解放費用も含みます。

ソースのAPI注記
[PersistentSegmentTree<T,Op>] Op(const T&,const T&)は結合的、identityは両側単位元。
T/Opはコピー可能。Tの破棄は例外を送出しない。演算・コピーの費用をO(1)として記す。
(n,op,identity)/(values,op,identity): 単位元列/配列を構築。O(1)/O(n)。
size()/empty()/allocated_nodes(): 長さ/空か/格納ノード数、O(1)。
Root: コピー可能な不変ハンドル。同じオブジェクトの有効な根だけを渡す。
empty_root()/latest_root(): 全要素単位元の根/直近のbuild・set・transformの根、O(1)。
build(values): 長さsize()の列の根を追加し返す。以前の根を保持、O(n)時間・追加領域。
set(root,i,value)/transform(root,i,f): 点代入/f(旧値)の根を返す。O(log(n+1))時間・追加領域。
get(root,i): 点の値。prod(root,l,r)/all_prod(root): 左から右への半開区間積/全体積。
get/prodはO(log(n+1))、all_prodはO(1)。空区間の積は単位元。
prodは共通の経路から区間両端へ分かれ、反復処理で順序を保って集約する。追加領域O(1)。
max_right(root,l,pred)/min_left(root,r,pred): pred(積)が真の最大右端/最小左端。
pred(identity)==true、区間を伸ばすと真から偽へ一度だけ変化する前提。O(log(n+1))。
reserve(nodes): 総ノード容量を予約。再確保時O(allocated_nodes())。ハンドルは失効しない。
reset(n)/clear(): 全根を無効化して単位元列/長さ0へ戻す。旧ノード数に比例する破棄費用。
コピーは独立。remap_from(original,root): 直接コピー元のコピー時に存在した根を移す、O(1)。
元のRootはコピー先へ直接渡せない。latest_root()/empty_root()はコピー先の根を返す。
moveは根を移動先へ引き継ぐ。move元には破棄・代入だけ行う。swapは根も交換する。
更新・構築の失敗時は追加ノードを取り消し、旧根とlatest_rootを維持する。
SKIP_RUNTIME_CHECKSで根の所属・添字・長さ・述語の単位元検査と所属用状態を除く。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Persistent Queue (PersistentSegmentTree) coverage_structure_persistent_queue.cpp 現行未照合・要再提出 AC
Point Add Range Sum persistent_segment_tree.cpp 現行未照合・要再提出 AC

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

ローカル・CI検査

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

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

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

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// 数学的参考: https://info.atcoder.jp/entry/algorithm_lectures/persistent_segment_tree
// 参考: https://nyaannyaan.github.io/library/segment-tree/persistent-segment-tree.hpp.html
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/persistent_segment_tree.md
//
// API一覧
// [PersistentSegmentTree<T,Op>] Op(const T&,const T&)は結合的、identityは両側単位元。
// T/Opはコピー可能。Tの破棄は例外を送出しない。演算・コピーの費用をO(1)として記す。
// (n,op,identity)/(values,op,identity): 単位元列/配列を構築。O(1)/O(n)。
// size()/empty()/allocated_nodes(): 長さ/空か/格納ノード数、O(1)。
// Root: コピー可能な不変ハンドル。同じオブジェクトの有効な根だけを渡す。
// empty_root()/latest_root(): 全要素単位元の根/直近のbuild・set・transformの根、O(1)。
// build(values): 長さsize()の列の根を追加し返す。以前の根を保持、O(n)時間・追加領域。
// set(root,i,value)/transform(root,i,f): 点代入/f(旧値)の根を返す。O(log(n+1))時間・追加領域。
// get(root,i): 点の値。prod(root,l,r)/all_prod(root): 左から右への半開区間積/全体積。
// get/prodはO(log(n+1))、all_prodはO(1)。空区間の積は単位元。
// prodは共通の経路から区間両端へ分かれ、反復処理で順序を保って集約する。追加領域O(1)。
// max_right(root,l,pred)/min_left(root,r,pred): pred(積)が真の最大右端/最小左端。
// pred(identity)==true、区間を伸ばすと真から偽へ一度だけ変化する前提。O(log(n+1))。
// reserve(nodes): 総ノード容量を予約。再確保時O(allocated_nodes())。ハンドルは失効しない。
// reset(n)/clear(): 全根を無効化して単位元列/長さ0へ戻す。旧ノード数に比例する破棄費用。
// コピーは独立。remap_from(original,root): 直接コピー元のコピー時に存在した根を移す、O(1)。
// 元のRootはコピー先へ直接渡せない。latest_root()/empty_root()はコピー先の根を返す。
// moveは根を移動先へ引き継ぐ。move元には破棄・代入だけ行う。swapは根も交換する。
// 更新・構築の失敗時は追加ノードを取り消し、旧根とlatest_rootを維持する。
// SKIP_RUNTIME_CHECKSで根の所属・添字・長さ・述語の単位元検査と所属用状態を除く。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <concepts>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <limits>
#include <span>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#if !defined(SKIP_RUNTIME_CHECKS) && !defined(SIRKIT_PERSISTENT_TREE_OWNER_DEFINED)
#define SIRKIT_PERSISTENT_TREE_OWNER_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
template<class Counter>
std::uint64_t take_persistent_tree_owner(Counter& next) {
    auto value = next.load(std::memory_order_relaxed);
    for (;;) {
        if (value == std::numeric_limits<std::uint64_t>::max())
            throw std::length_error("PersistentSegmentTree owner limit");
        if (next.compare_exchange_weak(value, value + 1, std::memory_order_relaxed)) return value;
    }
}
inline std::uint64_t persistent_tree_owner() {
    static std::atomic<std::uint64_t> next{1};
    return take_persistent_tree_owner(next);
}
}
#endif

#ifndef SIRKIT_PERSISTENT_SEGMENT_TREE_DEFINED
#define SIRKIT_PERSISTENT_SEGMENT_TREE_DEFINED
namespace detail {
inline void CheckPersistentTreeNodeCapacity(std::size_t size, std::size_t limit) {
    if (size == limit) throw std::length_error("PersistentSegmentTree node limit");
}
}

template<class T, class Op>
class PersistentSegmentTree {
    static_assert(std::copyable<T> && std::copy_constructible<Op>);
    static_assert(std::is_invocable_r_v<T, const Op&, const T&, const T&>);
    static_assert(std::is_nothrow_destructible_v<T>);
public:
    class Root {
        friend class PersistentSegmentTree;
        std::size_t index_ = 0;
#ifndef SKIP_RUNTIME_CHECKS
        std::uint64_t owner_ = 0;
        Root(std::size_t index, std::uint64_t owner) : index_(index), owner_(owner) {}
#else
        explicit Root(std::size_t index) : index_(index) {}
#endif
    public:
        Root() = default;
        friend constexpr bool operator==(const Root& a, const Root& b) noexcept {
            if (a.index_ != b.index_) return false;
#ifndef SKIP_RUNTIME_CHECKS
            return a.owner_ == b.owner_;
#else
            return true;
#endif
        }
    };
private:
    struct Node {
        T value;
        std::size_t left, right;
    };
    struct State {
        std::size_t n, latest = 0;
        Op op;
        T identity;
        std::vector<Node> nodes;
#ifndef SKIP_RUNTIME_CHECKS
        std::uint64_t owner = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::persistent_tree_owner();
        std::uint64_t copied_owner = 0;
        std::size_t copied_nodes = 0;
#endif
        State(std::size_t count, Op operation, T unit)
            : n(count), op(std::move(operation)), identity(std::move(unit)) {}
        State(const State& other)
            : n(other.n), latest(other.latest), op(other.op), identity(other.identity), nodes(other.nodes) {
#ifndef SKIP_RUNTIME_CHECKS
            copied_owner = other.owner; copied_nodes = other.nodes.size();
#endif
        }
    };
    std::unique_ptr<State> state_;

    Root handle(std::size_t index) const {
#ifndef SKIP_RUNTIME_CHECKS
        return Root(index, state_->owner);
#else
        return Root(index);
#endif
    }
    std::size_t checked_root(const Root& root) const {
#ifndef SKIP_RUNTIME_CHECKS
        // 同じ世代の根は公開後に削除されず、その添字は有効。
        if (root.owner_ != state_->owner)
            throw std::invalid_argument("PersistentSegmentTree root");
#endif
        return root.index_;
    }
    void check_index(std::size_t index) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (index >= size()) throw std::out_of_range("PersistentSegmentTree index");
#else
        static_cast<void>(index);
#endif
    }
    void check_range(std::size_t left, std::size_t right) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (left > right || right > size()) throw std::out_of_range("PersistentSegmentTree range");
#else
        static_cast<void>(left); static_cast<void>(right);
#endif
    }
    const T& value(std::size_t index) const {
        return index == 0 ? state_->identity : state_->nodes[index - 1].value;
    }
    std::size_t child(std::size_t index, bool right) const {
        return index == 0 ? 0 : (right ? state_->nodes[index - 1].right : state_->nodes[index - 1].left);
    }
    std::size_t append(T aggregate, std::size_t left, std::size_t right) {
        detail::CheckPersistentTreeNodeCapacity(state_->nodes.size(), state_->nodes.max_size());
        state_->nodes.push_back(Node{std::move(aggregate), left, right});
        return state_->nodes.size();
    }
    std::size_t merge(std::size_t left, std::size_t right) {
        T aggregate = std::invoke(std::as_const(state_->op), value(left), value(right));
        return append(std::move(aggregate), left, right);
    }
    void rollback(std::size_t count) noexcept {
        while (state_->nodes.size() > count) state_->nodes.pop_back();
    }
    std::size_t build_impl(std::span<const T> values, std::size_t left, std::size_t right) {
        if (left == right) return 0;
        if (right - left == 1) return append(values[left], 0, 0);
        const auto middle = left + (right - left) / 2;
        const auto a = build_impl(values, left, middle);
        const auto b = build_impl(values, middle, right);
        return merge(a, b);
    }
    template<class F>
    std::size_t transform_impl(std::size_t index, std::size_t position, F& function,
                               std::size_t left, std::size_t right) {
        if (right - left == 1) return append(std::invoke(function, value(index)), 0, 0);
        const auto middle = left + (right - left) / 2;
        auto a = child(index, false), b = child(index, true);
        if (position < middle) a = transform_impl(a, position, function, left, middle);
        else b = transform_impl(b, position, function, middle, right);
        return merge(a, b);
    }
    T prod_impl(std::size_t index, std::size_t begin, std::size_t end,
                std::size_t left, std::size_t right) const {
        if (begin == end || index == 0) return state_->identity;
        std::size_t middle;
        for (;;) {
            if (begin <= left && right <= end) return value(index);
            middle = left + (right - left) / 2;
            if (end <= middle) { index = child(index, false); right = middle; }
            else if (middle <= begin) { index = child(index, true); left = middle; }
            else break;
            if (index == 0) return state_->identity;
        }
        T first = state_->identity, second = state_->identity;
        auto current = child(index, false);
        auto lo = left, hi = middle;
        while (current != 0) {
            if (begin <= lo) {
                first = std::invoke(std::as_const(state_->op), value(current), first);
                break;
            }
            const auto split = lo + (hi - lo) / 2;
            if (begin < split) {
                const auto sibling = child(current, true);
                if (sibling != 0) first = std::invoke(std::as_const(state_->op), value(sibling), first);
                current = child(current, false); hi = split;
            } else { current = child(current, true); lo = split; }
        }
        current = child(index, true); lo = middle; hi = right;
        while (current != 0) {
            if (hi <= end) {
                second = std::invoke(std::as_const(state_->op), second, value(current));
                break;
            }
            const auto split = lo + (hi - lo) / 2;
            if (split < end) {
                const auto sibling = child(current, false);
                if (sibling != 0) second = std::invoke(std::as_const(state_->op), second, value(sibling));
                current = child(current, true); lo = split;
            } else { current = child(current, false); hi = split; }
        }
        return std::invoke(std::as_const(state_->op), first, second);
    }
    template<class Pred>
    std::size_t right_impl(std::size_t index, std::size_t begin, Pred& pred,
                           T& aggregate, std::size_t left, std::size_t right) const {
        if (right <= begin) return right;
        if (begin <= left) {
            T next = std::invoke(std::as_const(state_->op), aggregate, value(index));
            if (std::invoke(pred, std::as_const(next))) { aggregate = std::move(next); return right; }
            if (right - left == 1) return left;
        }
        const auto middle = left + (right - left) / 2;
        const auto result = right_impl(child(index, false), begin, pred, aggregate, left, middle);
        if (result < middle) return result;
        return right_impl(child(index, true), begin, pred, aggregate, middle, right);
    }
    template<class Pred>
    std::size_t left_impl(std::size_t index, std::size_t end, Pred& pred,
                          T& aggregate, std::size_t left, std::size_t right) const {
        if (end <= left) return left;
        if (right <= end) {
            T next = std::invoke(std::as_const(state_->op), value(index), aggregate);
            if (std::invoke(pred, std::as_const(next))) { aggregate = std::move(next); return left; }
            if (right - left == 1) return right;
        }
        const auto middle = left + (right - left) / 2;
        const auto result = left_impl(child(index, true), end, pred, aggregate, middle, right);
        if (result > middle) return result;
        return left_impl(child(index, false), end, pred, aggregate, left, middle);
    }
public:
    PersistentSegmentTree(std::size_t n, Op op, T identity)
        : state_(std::make_unique<State>(n, std::move(op), std::move(identity))) {}
    PersistentSegmentTree(std::span<const T> values, Op op, T identity)
        : PersistentSegmentTree(values.size(), std::move(op), std::move(identity)) { build(values); }
    PersistentSegmentTree(const std::vector<T>& values, Op op, T identity)
        : PersistentSegmentTree(std::span<const T>(values), std::move(op), std::move(identity)) {}
    PersistentSegmentTree(const PersistentSegmentTree& other)
        : state_(std::make_unique<State>(*other.state_)) {}
    PersistentSegmentTree& operator=(const PersistentSegmentTree& other) {
        if (this != &other) { auto next = std::make_unique<State>(*other.state_); state_.swap(next); }
        return *this;
    }
    PersistentSegmentTree(PersistentSegmentTree&&) noexcept = default;
    PersistentSegmentTree& operator=(PersistentSegmentTree&&) noexcept = default;
    void swap(PersistentSegmentTree& other) noexcept { state_.swap(other.state_); }
    friend void swap(PersistentSegmentTree& a, PersistentSegmentTree& b) noexcept { a.swap(b); }
    std::size_t size() const noexcept { return state_->n; }
    bool empty() const noexcept { return size() == 0; }
    std::size_t allocated_nodes() const noexcept { return state_->nodes.size(); }
    Root empty_root() const { return handle(0); }
    Root latest_root() const { return handle(state_->latest); }
    Root remap_from(const PersistentSegmentTree& original, const Root& root) const {
#ifndef SKIP_RUNTIME_CHECKS
        original.checked_root(root);
        if (state_->copied_owner != original.state_->owner || root.index_ > state_->copied_nodes)
            throw std::invalid_argument("PersistentSegmentTree copied root");
#else
        static_cast<void>(original);
#endif
        return handle(root.index_);
    }
    void reserve(std::size_t nodes) { state_->nodes.reserve(nodes); }
    void reset(std::size_t n) {
        auto next = std::make_unique<State>(n, state_->op, state_->identity);
        state_.swap(next);
    }
    void clear() { reset(0); }
    Root build(std::span<const T> values) {
#ifndef SKIP_RUNTIME_CHECKS
        if (values.size() != size()) throw std::invalid_argument("PersistentSegmentTree build length");
#endif
        const auto before = allocated_nodes();
        try { state_->latest = build_impl(values, 0, size()); }
        catch (...) { rollback(before); throw; }
        return latest_root();
    }
    Root build(const std::vector<T>& values) { return build(std::span<const T>(values)); }
    template<class F>
    Root transform(const Root& root, std::size_t position, F function) {
        const auto index = checked_root(root); check_index(position);
        const auto before = allocated_nodes();
        try { state_->latest = transform_impl(index, position, function, 0, size()); }
        catch (...) { rollback(before); throw; }
        return latest_root();
    }
    Root set(const Root& root, std::size_t position, const T& replacement) {
        return transform(root, position, [&replacement](const T&) -> const T& { return replacement; });
    }
    T get(const Root& root, std::size_t position) const {
        auto index = checked_root(root); check_index(position);
        std::size_t left = 0, right = size();
        while (right - left > 1) {
            const auto middle = left + (right - left) / 2;
            if (position < middle) { index = child(index, false); right = middle; }
            else { index = child(index, true); left = middle; }
        }
        return value(index);
    }
    T prod(const Root& root, std::size_t left, std::size_t right) const {
        const auto index = checked_root(root); check_range(left, right);
        return prod_impl(index, left, right, 0, size());
    }
    T all_prod(const Root& root) const { return value(checked_root(root)); }
    template<class Pred>
    std::size_t max_right(const Root& root, std::size_t left, Pred pred) const {
        const auto index = checked_root(root); check_range(left, size());
#ifndef SKIP_RUNTIME_CHECKS
        if (!std::invoke(pred, std::as_const(state_->identity)))
            throw std::invalid_argument("PersistentSegmentTree predicate identity");
#endif
        if (left == size()) return size();
        T aggregate = state_->identity;
        return right_impl(index, left, pred, aggregate, 0, size());
    }
    template<class Pred>
    std::size_t min_left(const Root& root, std::size_t right, Pred pred) const {
        const auto index = checked_root(root); check_range(0, right);
#ifndef SKIP_RUNTIME_CHECKS
        if (!std::invoke(pred, std::as_const(state_->identity)))
            throw std::invalid_argument("PersistentSegmentTree predicate identity");
#endif
        if (right == 0) return 0;
        T aggregate = state_->identity;
        return left_impl(index, right, pred, aggregate, 0, size());
    }
};
#endif

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