sirkit-cpp-library

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

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

Disjoint Sparse Table

DataStructure/Disjoint_Sparse_Table.cpp · ソース · 文書 現行ACあり Last Commit

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

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

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

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

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

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

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

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

DisjointSparseTable<T,Op>は、変更しない列の区間をO(1)で集約します。和・行列積・写像の合成などに使えます。区間は0始まりの半開区間[l,r)です。使用例を参照してください。

Opには括り方で結果が変わらない演算と、その演算の左右どちらの引数に置いてももう一方の値を変えない単位元を指定します。演算では要素の順序を保ちます。Sparse Tableと異なりop(x,x)==xは不要なので、和も扱えます。

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

コンストラクタ

explicit DisjointSparseTable(const std::vector<T>& values = {}, const T& identity = T{}, Op op = Op{});
DisjointSparseTable(const DisjointSparseTable&) = default;
DisjointSparseTable(DisjointSparseTable&& other);

引数を省略すると空列で構築し、valuesを渡すとその列で構築します。コピーした列は元の列から独立しています。

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

計算量: N要素にO(N log(N+1)+1)時間・領域。 ムーブ構築はO(1)、コピーは保持領域に比例。

get

const_reference get(std::size_t i) const;

元の要素のconst参照を返します。T=boolでは値を返します。

制約: 指定位置は0以上size()未満。

計算量: O(1)。

prod

T prod(std::size_t l, std::size_t r) const;

半開区間[l,r)を左から集約した値を返します。空区間は単位元です。

制約: 区間は0<=l<=r<=size()。点を指定する形は0<=p<size()。

計算量: O(1)。

all_prod

T all_prod() const;

列全体を先頭から集約した値を返します。空列は単位元です。

制約: 共通の前提を満たすこと。

計算量: O(1)。

max_right

template<class Pred> std::size_t max_right(std::size_t l, Pred pred) const;

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

制約: 端点は[0,size()]内。pred(単位元)=trueで、区間を伸ばしてfalseの後はtrueへ戻らないこと。

計算量: O(log(N+1))。述語の費用は別です。

min_left

template<class Pred> std::size_t min_left(std::size_t r, Pred pred) const;

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

制約: 端点は[0,size()]内。pred(単位元)=trueで、区間を伸ばしてfalseの後はtrueへ戻らないこと。

計算量: O(log(N+1))。述語の費用は別です。

size

std::size_t size() const noexcept;

要素数を返します。

制約: 共通の前提を満たすこと。

計算量: O(1)。

empty

bool empty() const noexcept;

空ならtrueを返します。

制約: 共通の前提を満たすこと。

計算量: O(1)。

values

std::vector<T> values() const;

元の列をvectorへコピーして返します。

制約: 共通の前提を満たすこと。

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

assign

void assign(const std::vector<T>& values);

指定した列で再構築します。

制約: 共通の前提を満たすこと。

計算量: O(旧N log(旧N+1)+新N log(新N+1)+1)時間・新列分の領域。

clear

void clear() noexcept;

空の状態へ戻します。容量や資源の扱いは末尾の所有・例外の説明に従います。

制約: 共通の前提を満たすこと。

計算量: 旧列の保持領域の破棄に比例。

swap

void swap(DisjointSparseTable& other);

内容と設定を交換します。

制約: 共通の前提を満たすこと。

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

DisjointSparseTable<std::int64_t, std::plus<std::int64_t>> table(
    std::vector<std::int64_t>{2,0,3,5});
auto sum = table.prod(1,4); // 8 = 0+3+5。

前提と計算量

演算・コピーをO(1)として、構築はO(N log(N+1)+1)時間・領域です。再構築は旧領域の破棄も含めO(旧N log(旧N+1)+新N log(新N+1)+1)です。

境界探索の述語は同じ値に同じ結果を返し、pred(identity)がtrueで、区間を伸ばしてfalseになった後はtrueへ戻らないことが前提です。単調性を確認する全要素走査は行いません。

Opはconst呼出可能な型を使います。添字・区間・述語の単位元条件は既定で検査し、SKIP_RUNTIME_CHECKSで除きます。参照は再構築・clear・移動・交換後まで保持しないでください。コピーは独立、移動元は空として再利用できます。演算等の例外時に内容の強い保証は行いません。

数学的参考はAtCoder Algorithm Lecturesです。実装は本ライブラリ用のCC0です。

operator=

DisjointSparseTable& operator=(const DisjointSparseTable& other);
DisjointSparseTable& operator=(DisjointSparseTable&& other);

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

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

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

ソースのAPI注記
[DisjointSparseTable<T, Op>]
DisjointSparseTable(vector<T>={}, identity=T{}, op=Op{}): 静的列を構築。O(n log(n+1)+1)時間・領域。
Op(a,b)はconst呼出可能かつ結合的、identityは左右の単位元。非可換でも可。 演算/コピーをO(1)とする。
size()/empty(): 要素数/空か。get(i): const T&(T=boolは値)。prod(l,r): 半開区間[l,r)の積。all_prod(): 全積。O(1)。
prodの空区間・空列の全積はidentity。参照はassign/clear/交換/移動で無効になり得る。添字は0始まり。
max_right(l,pred)/min_left(r,pred): predが真の最大右端/最小左端。O(log(n+1))。pred(identity)==trueと境界の単調性が前提。
values(): 元の列をコピー、O(n+1)。assign(vector<T>): 再構築。O(旧n log(旧n+1)+n log(n+1)+1)。点更新は行わない。
clear()/swap(other): 空へ戻す/内容交換。O(旧n log(旧n+1)+1)/O(1)。コピーは独立、移動元は空。演算等の例外時は内容の強い保証なし。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Queue Operate All Composite (DisjointSparseTable) coverage_structure_disjoint_composite.cpp ✓ 現行AC AC
Static RMQ disjoint_sparse_table.cpp ✓ 現行AC 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/disjoint_sparse_table
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/disjoint_sparse_table.md
//
// API一覧
// [DisjointSparseTable<T, Op>]
// DisjointSparseTable(vector<T>={}, identity=T{}, op=Op{}): 静的列を構築。O(n log(n+1)+1)時間・領域。
// Op(a,b)はconst呼出可能かつ結合的、identityは左右の単位元。非可換でも可。 演算/コピーをO(1)とする。
// size()/empty(): 要素数/空か。get(i): const T&(T=boolは値)。prod(l,r): 半開区間[l,r)の積。all_prod(): 全積。O(1)。
// prodの空区間・空列の全積はidentity。参照はassign/clear/交換/移動で無効になり得る。添字は0始まり。
// max_right(l,pred)/min_left(r,pred): predが真の最大右端/最小左端。O(log(n+1))。pred(identity)==trueと境界の単調性が前提。
// values(): 元の列をコピー、O(n+1)。assign(vector<T>): 再構築。O(旧n log(旧n+1)+n log(n+1)+1)。点更新は行わない。
// clear()/swap(other): 空へ戻す/内容交換。O(旧n log(旧n+1)+1)/O(1)。コピーは独立、移動元は空。演算等の例外時は内容の強い保証なし。


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


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_DISJOINT_SPARSE_TABLE_DEFINED
#define SIRKIT_DISJOINT_SPARSE_TABLE_DEFINED
template<class T, class Op>
class DisjointSparseTable {
    [[no_unique_address]] Op op_;
    T identity_;
    // 第0行は、原列と半幅1の行を兼ねる。
    std::vector<std::vector<T>> table_;
    std::size_t length_ = 0;
    static constexpr bool fill_identity_rows_ =
        std::is_integral_v<T> && !std::is_same_v<T, bool> && sizeof(T) >= 4;
    void check_range(std::size_t l, std::size_t r) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (l > r || r > size()) throw std::out_of_range("DisjointSparseTable: range");
#else
        (void)l; (void)r;
#endif
    }
    T range_unchecked(std::size_t l, std::size_t r) const {
        if (l == r) return identity_;
        const auto last = r - 1;
        if (l == last) return table_.front()[l];
        const auto k = std::bit_width(l ^ last) - 1;
        return op_(table_[k][l], table_[k][last]);
    }
public:
    using const_reference = typename std::vector<T>::const_reference;
    explicit DisjointSparseTable(const std::vector<T>& values = {}, const T& identity = T{}, Op op = Op{})
        : op_(std::move(op)), identity_(identity), length_(values.size()) {
        const auto n = values.size();
        if (!n) return;
        table_.reserve(n <= 1 ? 1 : std::bit_width(n - 1));
        table_.push_back(values);
        if (n <= 2) return;
        for (std::size_t half = 2;;) {
            if constexpr (fill_identity_rows_) table_.emplace_back(n, identity_);
            else table_.push_back(values);
            auto& row = table_.back();
            for (std::size_t begin = 0; begin < n;) {
                const auto middle = begin + std::min(half, n - begin);
                const auto end = middle + std::min(half, n - middle);
                // 集約の起点だけを設定し、残りは左右の走査で埋める。
                if constexpr (fill_identity_rows_) row[middle - 1] = values[middle - 1];
                for (auto i = middle; i > begin + 1; --i) row[i - 2] = op_(values[i - 2], row[i - 1]);
                if (middle < end) {
                    if constexpr (fill_identity_rows_) row[middle] = values[middle];
                    for (auto i = middle + 1; i < end; ++i) row[i] = op_(row[i - 1], values[i]);
                }
                begin = end;
            }
            if (half > (n - 1) / 2) break;
            half *= 2;
        }
    }
    DisjointSparseTable(const DisjointSparseTable&) = default;
    DisjointSparseTable& operator=(const DisjointSparseTable& other) {
        if (this != &other) { DisjointSparseTable replacement(other); swap(replacement); }
        return *this;
    }
    DisjointSparseTable(DisjointSparseTable&& other)
        : op_(other.op_), identity_(other.identity_), table_(std::move(other.table_)), length_(other.length_) {
        other.table_.clear(); other.length_ = 0;
    }
    DisjointSparseTable& operator=(DisjointSparseTable&& other) {
        if (this != &other) { DisjointSparseTable replacement(std::move(other)); swap(replacement); }
        return *this;
    }
    std::size_t size() const noexcept { return length_; }
    bool empty() const noexcept { return size() == 0; }
    const_reference get(std::size_t i) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (i >= size()) throw std::out_of_range("DisjointSparseTable: index");
#endif
        return table_.front()[i];
    }
    T prod(std::size_t l, std::size_t r) const { check_range(l, r); return range_unchecked(l, r); }
    T all_prod() const { return range_unchecked(0, size()); }
    template<class Pred> std::size_t max_right(std::size_t l, Pred pred) const {
        check_range(l, l);
#ifndef SKIP_RUNTIME_CHECKS
        if (!pred(identity_)) throw std::invalid_argument("DisjointSparseTable: predicate(identity)");
#endif
        auto low = l, high = size();
        while (low < high) {
            const auto distance = high - low;
            const auto middle = low + distance / 2 + distance % 2;
            if (pred(range_unchecked(l, middle))) low = middle;
            else high = middle - 1;
        }
        return low;
    }
    template<class Pred> std::size_t min_left(std::size_t r, Pred pred) const {
        check_range(r, r);
#ifndef SKIP_RUNTIME_CHECKS
        if (!pred(identity_)) throw std::invalid_argument("DisjointSparseTable: predicate(identity)");
#endif
        std::size_t low = 0, high = r;
        while (low < high) {
            const auto middle = low + (high - low) / 2;
            if (pred(range_unchecked(middle, r))) high = middle;
            else low = middle + 1;
        }
        return low;
    }
    std::vector<T> values() const { return table_.empty() ? std::vector<T>{} : table_.front(); }
    void assign(const std::vector<T>& values) { DisjointSparseTable replacement(values, identity_, op_); swap(replacement); }
    void clear() noexcept { table_.clear(); length_ = 0; }
    void swap(DisjointSparseTable& other) noexcept(std::is_nothrow_swappable_v<Op> && std::is_nothrow_swappable_v<T>) {
        using std::swap;
        swap(op_, other.op_); swap(identity_, other.identity_);
        table_.swap(other.table_); swap(length_, other.length_);
    }
};
#endif

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