sirkit-cpp-library

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

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

Sparse Table

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

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

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

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

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

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

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

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

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

SparseTable<T,Op>は、変更しない列の区間の最小値・最大値・gcdなどをO(1)で求めます。区間は0始まりの半開区間[l,r)です。使用例を参照してください。

Opには結合的な演算を指定します。同じ値を重ねても結果が変わらないop(x,x)==xが必要で、この性質をべき等性と呼びます。和はこの条件を満たさないため、Disjoint Sparse Tableを使います。左右の引数を交換できる必要はありません。単位元identityには、左右どちらの引数に置いてももう一方の値を変えない値を指定します。

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

コンストラクタ

explicit SparseTable(const std::vector<T>& values = {}, const T& identity = T{}, Op op = Op{});
SparseTable(const SparseTable&) = default;
SparseTable(SparseTable&& 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(SparseTable& other);

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

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

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

struct Minimum { int operator()(int a,int b) const { return std::min(a,b); } };
SparseTable<int,Minimum> table(
    std::vector<int>{4,2,7,1,8},std::numeric_limits<int>::max());
auto minimum = table.prod(1,4); // 1。

前提と計算量

演算・コピーを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・移動・交換後まで保持しないでください。コピーは独立、移動元は空として再利用できます。演算等の例外時に内容の強い保証は行いません。

32bit以下の整数型(bool以外)では、条件が合えば対応するGCC/Clang・CPUでAVX2を使って構築します。SIRKIT_DISABLE_SIMDで専用経路とCPU判定を除外できます。非対応環境やその他の値型は標準C++の経路で処理します。

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

operator=

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

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

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

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

ソースのAPI注記
[SparseTable<T, Op>]
SparseTable(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)。コピーは独立、移動元は空。演算等の例外時は内容の強い保証なし。
SIMD: 32bit以下の整数(bool以外)の構築に条件付きAVX2経路。SIRKIT_DISABLE_SIMDで専用経路とCPU判定を除く。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Static RMQ 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/sparse_table
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/sparse_table.md
//
// API一覧
// [SparseTable<T, Op>]
// SparseTable(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)。コピーは独立、移動元は空。演算等の例外時は内容の強い保証なし。
// SIMD: 32bit以下の整数(bool以外)の構築に条件付きAVX2経路。SIRKIT_DISABLE_SIMDで専用経路とCPU判定を除く。


// 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_SPARSE_TABLE_DEFINED
#define SIRKIT_SPARSE_TABLE_DEFINED
template<class T, class Op>
class SparseTable {
    [[no_unique_address]] Op op_;
    T identity_;
    std::vector<std::vector<T>> table_;
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
#if defined(__GNUC__) && !defined(__clang__)
    [[gnu::target("avx2"), gnu::optimize("O3")]]
#else
    [[gnu::target("avx2")]]
#endif
    // 入出力は別々のvectorが所有する領域への非所有ポインタ。
    static void fill_row_avx2(T* target, const T* left, const T* right, std::size_t count, Op& op) {
        for (std::size_t i = 0; i < count; ++i) target[i] = T(op(left[i], right[i]));
    }
    static bool supports_avx2() noexcept {
        static const bool available = [] {
            __builtin_cpu_init();
            return __builtin_cpu_supports("avx2") != 0;
        }();
        return available;
    }
#endif
    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("SparseTable: 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 k = std::bit_width(r - l) - 1;
        const auto width = std::size_t{1} << k;
        return op_(table_[k][l], table_[k][r - width]);
    }
public:
    using const_reference = typename std::vector<T>::const_reference;
    explicit SparseTable(const std::vector<T>& values = {}, const T& identity = T{}, Op op = Op{})
        : op_(std::move(op)), identity_(identity) {
        const auto n = values.size();
        if (!n) return;
        table_.reserve(std::bit_width(n));
        table_.push_back(values);
        for (std::size_t width = 2; width <= n;) {
            const auto half = width / 2;
            const auto count = n - width + 1;
            std::vector<T> row;
            bool filled = false;
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
            using Result = decltype(op_(std::declval<const std::vector<T>&>()[std::size_t{}],
                                        std::declval<const std::vector<T>&>()[std::size_t{}]));
            if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool> && sizeof(T) <= 4 &&
                          std::is_same_v<std::remove_cvref_t<Result>, T>) {
                if (count >= 256 && supports_avx2()) {
                    row = std::vector<T>(count, identity_);
                    const auto& previous = table_.back();
                    fill_row_avx2(row.data(), previous.data(), previous.data() + half, count, op_);
                    filled = true;
                }
            }
#endif
            if (!filled) {
                row.reserve(count);
                const auto& previous = table_.back();
                for (std::size_t i = 0; i < count; ++i) row.emplace_back(op_(previous[i], previous[i + half]));
            }
            table_.push_back(std::move(row));
            if (width > n / 2) break;
            width *= 2;
        }
    }
    SparseTable(const SparseTable&) = default;
    SparseTable& operator=(const SparseTable& other) {
        if (this != &other) { SparseTable replacement(other); swap(replacement); }
        return *this;
    }
    SparseTable(SparseTable&& other)
        : op_(other.op_), identity_(other.identity_), table_(std::move(other.table_)) {
        other.table_.clear();
    }
    SparseTable& operator=(SparseTable&& other) {
        if (this != &other) { SparseTable replacement(std::move(other)); swap(replacement); }
        return *this;
    }
    std::size_t size() const noexcept { return (table_.empty() ? 0 : table_.front().size()); }
    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("SparseTable: 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("SparseTable: 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("SparseTable: 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) { SparseTable replacement(values, identity_, op_); swap(replacement); }
    void clear() noexcept { table_.clear(); }
    void swap(SparseTable& 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_);
    }
};
#endif

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