sirkit-cpp-library

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

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

二次元スパーステーブル

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

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

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

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

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

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

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

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

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

更新のない表を前処理し、長方形内の最小値・最大値・最大公約数などを O(1) で求めます。演算 op は二項演算で、結合的かつ可換、さらに同じ値を重ねても値が変わらないことが前提です。

SparseTable2D

SparseTable2D(const std::vector<std::vector<T>> &grid, Op op);
SparseTable2D(std::size_t height, std::size_t width, std::span<const T> row_major, Op op);

各行の長さが同じ配列、または全行を順に連結した height * width 要素から構築します。検査有効時は形状の不一致で std::invalid_argument を送出します。表に必要な要素数を格納できない場合は std::length_error です。

H 行 W 列で、演算および要素のコピーが定数時間なら、時間は O(H+1+HW log(H+1) log(W+1))、領域は O(1+HW log(H+1) log(W+1)) です。

prod

T prod(std::size_t top, std::size_t left, std::size_t bottom, std::size_t right) const;

半開矩形 [top,bottom) × [left,right) の集約値を返します。矩形は非空で全体の範囲内が前提です。検査有効時は違反すると std::out_of_range を送出します。O(1) 時間です。

大きさ

  • height() は行数を返します。O(1) 時間です。
  • width() は列数を返します。O(1) 時間です。
  • empty() は要素がないかを判定します。O(1) 時間です。

使用例

const std::vector<std::vector<int>> grid{{4, 2, 8}, {6, 5, 1}};
const sirkit::SparseTable2D table(grid, [](int a, int b) { return std::min(a, b); });
assert(table.prod(0, 0, 2, 2) == 2);

完全な使用例

ソースのAPI注記
SparseTable2D<T,Op>(grid,op): 長方形の行列から構築する。
SparseTable2D<T,Op>(height,width,row_major,op): 行を順に連結したheight*width要素から構築する。
Opはconstで呼べる結合的・可換・冪等な二項演算。演算とTのコピーはO(1)とする。
H行W列の構築は空行を含めO(H+1+HW log(H+1) log(W+1))時間・O(1+HW log(H+1) log(W+1))領域。
prod(top,left,bottom,right): [top,bottom) × [left,right) の集約。非空で範囲内。O(1)。
height()/width()/empty(): 行数・列数・要素がないか。O(1)。
検査有効時は形状不一致でinvalid_argument、範囲外・空矩形の照会でout_of_range。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Stamp Game sparse_table_2d_stamps.cpp 未提出 —

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

ローカル・CI検査

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

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

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

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/sparse_table_2d.md
//
// API一覧
// SparseTable2D<T,Op>(grid,op): 長方形の行列から構築する。
// SparseTable2D<T,Op>(height,width,row_major,op): 行を順に連結したheight*width要素から構築する。
// Opはconstで呼べる結合的・可換・冪等な二項演算。演算とTのコピーはO(1)とする。
// H行W列の構築は空行を含めO(H+1+HW log(H+1) log(W+1))時間・O(1+HW log(H+1) log(W+1))領域。
// prod(top,left,bottom,right): [top,bottom) × [left,right) の集約。非空で範囲内。O(1)。
// height()/width()/empty(): 行数・列数・要素がないか。O(1)。
// 検査有効時は形状不一致でinvalid_argument、範囲外・空矩形の照会でout_of_range。


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


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_SPARSE_TABLE_2D_DEFINED
#define SIRKIT_SPARSE_TABLE_2D_DEFINED

template <class T, class Op>
class SparseTable2D
{
public:
    explicit SparseTable2D(const std::vector<std::vector<T>> &grid, Op op)
        : op_(std::move(op)), height_(grid.size()), width_(grid.empty() ? 0 : grid.front().size())
    {
        std::vector<T> base;
        base.reserve(Area(height_, width_));
        for (const auto &row : grid)
        {
#ifndef SKIP_RUNTIME_CHECKS
            if (row.size() != width_)
            {
                throw std::invalid_argument("SparseTable2D: ragged grid");
            }
#endif
            base.insert(base.end(), row.begin(), row.end());
        }
        Build(std::move(base));
    }

    SparseTable2D(std::size_t height, std::size_t width, std::span<const T> row_major, Op op)
        : op_(std::move(op)), height_(height), width_(width)
    {
        const auto area = Area(height_, width_);
#ifndef SKIP_RUNTIME_CHECKS
        if (row_major.size() != area)
        {
            throw std::invalid_argument("SparseTable2D: grid size mismatch");
        }
#endif
        Build(std::vector<T>(row_major.begin(), row_major.first(area).end()));
    }

    [[nodiscard]] T prod(std::size_t top, std::size_t left, std::size_t bottom, std::size_t right) const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (top >= bottom || left >= right || bottom > height_ || right > width_ || levels_.empty())
        {
            throw std::out_of_range("SparseTable2D: invalid rectangle");
        }
#endif
        const auto r_level = static_cast<std::size_t>(std::bit_width(bottom - top) - 1);
        const auto c_level = static_cast<std::size_t>(std::bit_width(right - left) - 1);
        const auto last_row = bottom - (std::size_t{1} << r_level);
        const auto last_column = right - (std::size_t{1} << c_level);
        const auto &level = levels_[Index(r_level, c_level)];
        return std::invoke(op_, std::invoke(op_, level.at(top, left), level.at(top, last_column)),
                           std::invoke(op_, level.at(last_row, left), level.at(last_row, last_column)));
    }

    [[nodiscard]] std::size_t height() const noexcept
    {
        return height_;
    }

    [[nodiscard]] std::size_t width() const noexcept
    {
        return width_;
    }

    [[nodiscard]] bool empty() const noexcept
    {
        return levels_.empty();
    }

private:
    struct Level
    {
        std::size_t columns = 0;
        std::vector<T> values;

        [[nodiscard]] typename std::vector<T>::const_reference at(std::size_t row, std::size_t column) const
        {
            return values[row * columns + column];
        }
    };

    [[nodiscard]] static std::size_t Area(std::size_t height, std::size_t width)
    {
        if (width != 0 && height > std::vector<T>().max_size() / width)
        {
            throw std::length_error("SparseTable2D: grid too large");
        }
        return height * width;
    }

    [[nodiscard]] std::size_t Index(std::size_t r_level, std::size_t c_level) const noexcept
    {
        return r_level * static_cast<std::size_t>(std::bit_width(width_)) + c_level;
    }

    void Build(std::vector<T> base)
    {
        if (height_ == 0 || width_ == 0)
        {
            return;
        }
        const auto r_levels = static_cast<std::size_t>(std::bit_width(height_));
        const auto c_levels = static_cast<std::size_t>(std::bit_width(width_));
        levels_.resize(r_levels * c_levels);
        levels_.front() = {width_, std::move(base)};
        for (std::size_t i = 0; i < r_levels; ++i)
        {
            for (std::size_t j = 0; j < c_levels; ++j)
            {
                if (i == 0 && j == 0)
                {
                    continue;
                }
                const auto rows = height_ - (std::size_t{1} << i) + 1;
                auto &level = levels_[Index(i, j)];
                level.columns = width_ - (std::size_t{1} << j) + 1;
                level.values.reserve(rows * level.columns);
                const std::size_t dr = j == 0 ? std::size_t{1} << (i - 1) : 0;
                const std::size_t dc = j == 0 ? 0 : std::size_t{1} << (j - 1);
                const auto &previous = levels_[j == 0 ? Index(i - 1, j) : Index(i, j - 1)];
                for (std::size_t row = 0; row < rows; ++row)
                {
                    for (std::size_t column = 0; column < level.columns; ++column)
                    {
                        level.values.push_back(std::invoke(op_, previous.at(row, column),
                                                           previous.at(row + dr, column + dc)));
                    }
                }
            }
        }
    }

    Op op_;
    std::size_t height_, width_;
    std::vector<Level> levels_;
};

#endif

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