sirkit-cpp-library

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

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

連長圧縮キュー

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

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

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

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

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

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

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

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

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

同じ値が続く部分を「値と個数」の組で保存します。値を一括で末尾に追加し、先頭から指定個数を取り出せます。

RunLengthQueue<T>

空のキューを作ります。T は移動構築と const 値どうしの == 比較ができる型です。コピー可能な値型ならキューもコピーできます。移動後、元のキューは空になります。

size

格納した要素の総数を std::uint64_t で返します。

empty

空かどうかを返します。

run_count

同じ値が連続するグループの数を返します。

front

先頭の値を const T & で返します。空の場合、検査が有効なら std::out_of_range を送出します。

front_count

先頭に連続する同じ値の個数を返します。空なら0です。size から front_count まで各 $O(1)$ 時間です。

push_back

push_back(value, count = 1) で値を count 個追加します。末尾と等しければ同じグループに入ります。$O(1)$ 時間です。検査が有効なら、総数が UINT64_MAX を超える追加に std::length_error を送出します。

pop_front

pop_front(count = 1) で先頭から count 個を削除します。

consume_front

consume_front(count, visitor) で削除するグループごとに visitor(const T &value, std::uint64_t copies) を呼びます。先頭から順に呼び、グループの一部を取り出したときはその個数を渡します。コールバックから同じキューを変更しないでください。コールバックが例外を送出すると、正常に戻った呼び出しの分だけ削除が済んだ状態になります。

削除はいずれも触れたグループ数を $r$ として $O(r+1)$ 時間です。空からの追加と削除だけを繰り返した場合、合計時間は操作回数に比例します。保存する値はグループにつき一つで、内部領域は同時に保持したグループ数の最大に比例します。計算量は値の移動・比較とコールバックを $O(1)$ とした場合です。

検査が有効なら、要素数を超える削除に std::out_of_range を送出します。

使用例

sirkit::RunLengthQueue<int> queue;
queue.push_back(3, 2);
queue.push_back(5, 4);
std::uint64_t sum = 0;
queue.consume_front(3, [&](int value, std::uint64_t count)
{
    sum += static_cast<std::uint64_t>(value) * count;
});
assert(sum == 11 && queue.front_count() == 3);

実装・使用例の全体・Verify

ソースのAPI注記
RunLengthQueue<T>(): 空で構築。同じ値の連続を1組にまとめる。Tのconst比較==が必要。
size()/empty()/run_count(): 要素数(uint64_t)/空か/連続グループ数。O(1)。
front()/front_count(): 先頭の値/その連続個数。空のfront()はout_of_range、front_count()は0。O(1)。
push_back(value,count=1): valueをcount個追加。O(1)。検査有効時は要素数上限を超えるとlength_error。
pop_front(count=1): 先頭count個を削除。consume_front(count,visitor): 削除する各組にvisitor(const T&,個数)を呼ぶ。
削除は触る連続グループ数+1に比例。空からの追加・削除全体では操作回数に比例。count<=size()。
保存する値は現在の連続グループ数。内部領域は同時保持グループ数の最大+1に比例。コールバックは同じキューを変更しないこと。例外時は成功済みの呼出し分だけ削除。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Large Queue run_length_queue.cpp 未提出 —

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

ローカル・CI検査

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

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

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

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// 参考(運用例): https://atcoder.jp/contests/abc413/tasks/abc413_c
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/run_length_queue.md
//
// API一覧
// RunLengthQueue<T>(): 空で構築。同じ値の連続を1組にまとめる。Tのconst比較==が必要。
// size()/empty()/run_count(): 要素数(uint64_t)/空か/連続グループ数。O(1)。
// front()/front_count(): 先頭の値/その連続個数。空のfront()はout_of_range、front_count()は0。O(1)。
// push_back(value,count=1): valueをcount個追加。O(1)。検査有効時は要素数上限を超えるとlength_error。
// pop_front(count=1): 先頭count個を削除。consume_front(count,visitor): 削除する各組にvisitor(const T&,個数)を呼ぶ。
// 削除は触る連続グループ数+1に比例。空からの追加・削除全体では操作回数に比例。count<=size()。
// 保存する値は現在の連続グループ数。内部領域は同時保持グループ数の最大+1に比例。コールバックは同じキューを変更しないこと。例外時は成功済みの呼出し分だけ削除。


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


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

template <typename T>
class RunLengthQueue
{
    using Count = std::uint64_t;
    struct Run
    {
        T value;
        Count end;
    };

    std::deque<Run> runs_;
    Count head_ = 0;

public:
    RunLengthQueue() = default;
    RunLengthQueue(const RunLengthQueue &) requires std::copy_constructible<T> = default;

    RunLengthQueue(RunLengthQueue &&other)
        : runs_(std::move(other.runs_)), head_(std::exchange(other.head_, 0))
    {
        other.runs_.clear();
    }

    RunLengthQueue &operator=(const RunLengthQueue &other) requires std::copy_constructible<T>
    {
        if (this != &other)
        {
            auto copied = other.runs_;
            runs_.swap(copied);
            head_ = other.head_;
        }
        return *this;
    }

    RunLengthQueue &operator=(RunLengthQueue &&other)
    {
        if (this != &other)
        {
            runs_ = std::move(other.runs_);
            head_ = std::exchange(other.head_, 0);
            other.runs_.clear();
        }
        return *this;
    }

    [[nodiscard]] Count size() const noexcept
    {
        return runs_.empty() ? 0 : runs_.back().end - head_;
    }

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

    [[nodiscard]] std::size_t run_count() const noexcept
    {
        return runs_.size();
    }

    [[nodiscard]] const T &front() const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (runs_.empty())
        {
            throw std::out_of_range("RunLengthQueue: empty");
        }
#endif
        return runs_.front().value;
    }

    [[nodiscard]] Count front_count() const noexcept
    {
        return runs_.empty() ? 0 : runs_.front().end - head_;
    }

    void push_back(T value, Count count = 1)
    {
        if (count == 0)
        {
            return;
        }
        const Count previous = size();
#ifndef SKIP_RUNTIME_CHECKS
        if (count > std::numeric_limits<Count>::max() - previous)
        {
            throw std::length_error("RunLengthQueue: too many elements");
        }
#endif
        // 通算位置は周回してよい。差を取ると現在の個数に戻る。
        const Count end = head_ + previous + count;
        if (!runs_.empty() && std::as_const(runs_.back().value) == std::as_const(value))
        {
            runs_.back().end = end;
        }
        else
        {
            runs_.push_back(Run{std::move(value), end});
        }
    }

    template <typename Visitor>
    void consume_front(Count count, Visitor &&visitor)
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (count > size())
        {
            throw std::out_of_range("RunLengthQueue: not enough elements");
        }
#endif
        while (count != 0)
        {
            const auto &run = runs_.front();
            const Count removed = std::min(count, run.end - head_);
            std::invoke(visitor, run.value, removed);
            head_ += removed;
            count -= removed;
            if (head_ == run.end)
            {
                runs_.pop_front();
            }
        }
    }

    void pop_front(Count count = 1)
    {
        consume_front(count, [](const T &, Count) noexcept
        {
        });
    }
};

#endif

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