競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
取りうる値が少ない列で、一点代入と区間照会を扱います。値が等しい要素も続けて選べます。たとえば {2, 0, 1, 1, 2} から {0, 1, 1, 2} を選ぶと長さは4です。
RangeNondecreasingSubsequence<A>RangeNondecreasingSubsequence();
explicit RangeNondecreasingSubsequence(std::span<const int> symbols);
長さ $n$ の列を保持します。値は 0 以上 A 未満で、1 <= A <= 256、n <= INT_MAX が必要です。構築は $O(A^3(n+1))$ 時間、保管は $O(A^2(n+1))$ 領域なので、小さい A に向きます。
size列の長さを $O(1)$ 時間で返します。
empty空の列かどうかを $O(1)$ 時間で返します。
setvoid set(int position, int symbol);
位置 position の値を symbol に代入します。$O(A^3\log(n+1))$ 時間です。
longestint longest(int left, int right) const;
int longest(int left, int right, int low, int high) const;
半開区間 [left, right) の最長広義単調増加部分列の長さを返します。4引数版では low 以上 high 以下の値から選びます。どちらも $O(A^3\log(n+1))$ 時間で、空区間の長さは0です。
replacement_countint replacement_count(int left, int right) const;
半開区間 [left, right) を広義単調増加列にする最少置換回数です。区間長から longest(left, right) を引きます。$O(A^3\log(n+1))$ 時間です。
all列全体の最長広義単調増加部分列の長さを $O(A^2)$ 時間で返します。
const std::array symbols{2, 0, 1, 1, 2};
sirkit::RangeNondecreasingSubsequence<3> range(symbols);
assert(range.replacement_count(0, 5) == 1);
range.set(0, 0);
assert(range.all() == 5);
位置の添字は0始まりです。検査を有効にすると、範囲外の位置・区間・値には std::out_of_range、low > high には std::invalid_argument を送出します。
RangeNondecreasingSubsequence<A>(symbols): 値が0以上A未満の列を保持。1<=A<=256、n<=INT_MAX。 構築はO(A^3*(n+1))時間、O(A^2*(n+1))領域。空構築可。区間は0始まりの半開。 size()/empty(): 長さ/空か。O(1)。set(i,x): 位置iへxを代入。 longest(l,r): 最長広義単調増加部分列の長さ。longest(l,r,low,high): 値も閉区間[low,high]に限定。 replacement_count(l,r): 広義単調増加列にする最少置換回数。上の更新・照会はO(A^3*log(n+1))。 all(): 列全体の最長長さ。O(A^2)。空区間は長さ0。コピーは独立、ムーブ元は空。 [同梱のSegment Tree] [segtree<S, op, e>(ACL形式、sirkit内に定義)] segtree()/segtree(int n)/segtree(vector<S>): 空列/n個の単位元/列から構築。0<=n<=INT_MAX、O(n+1)時間・領域。 S op(S,S)は結合的、S e()は左右の単位元。同じ呼び出し形式の関数オブジェクトも可。演算/コピーはO(1)。 点添字は0<=p<size()、区間は0<=l<=r<=size()の半開区間。 set(int p,S x): 点代入、O(log(n+1))。get(int p): 点のS値、O(1)。prod(int l,int r): 左からの区間積、O(log(n+1))。 all_prod(): 全積のS値、O(1)。空区間・空列の積はe()。積は非可換でもよい。 max_right<pred>(int l)/min_left<pred>(int r): bool pred(S)を使う境界探索。述語を第2引数に渡す形式も可。戻り値はint、O(log(n+1))。 探索はpred(e())==trueで、区間を延ばすと真から偽へ一度だけ変化すること。述語に副作用を持たせない。 [追加機能] size()/empty(): intの要素数/空か、O(1)。transform(int p,f): 点をf(現在値)へ更新、O(log(n+1))。 values(): 列のコピー、O(n+1)。assign(vector<S>)/reset(int n)/reset(): 列/n個/現在の長さの単位元へ再構築、O(旧n+n+1)。 clear()/swap(other): 容量を保持して空へ/交換、O(旧n+1)/O(1)。コピーは独立、移動元は空。値の演算等が投げる場合は内容の強い保証なし。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Range ABCD String Query | range_nondecreasing_subsequence.cpp | 未提出 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// 参考(問い合わせの用途): https://yukicoder.me/problems/no/2992
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/range_nondecreasing_subsequence.md
//
// API一覧
// RangeNondecreasingSubsequence<A>(symbols): 値が0以上A未満の列を保持。1<=A<=256、n<=INT_MAX。
// 構築はO(A^3*(n+1))時間、O(A^2*(n+1))領域。空構築可。区間は0始まりの半開。
// size()/empty(): 長さ/空か。O(1)。set(i,x): 位置iへxを代入。
// longest(l,r): 最長広義単調増加部分列の長さ。longest(l,r,low,high): 値も閉区間[low,high]に限定。
// replacement_count(l,r): 広義単調増加列にする最少置換回数。上の更新・照会はO(A^3*log(n+1))。
// all(): 列全体の最長長さ。O(A^2)。空区間は長さ0。コピーは独立、ムーブ元は空。
//
// [同梱のSegment Tree]
// [segtree<S, op, e>(ACL形式、sirkit内に定義)]
// segtree()/segtree(int n)/segtree(vector<S>): 空列/n個の単位元/列から構築。0<=n<=INT_MAX、O(n+1)時間・領域。
// S op(S,S)は結合的、S e()は左右の単位元。同じ呼び出し形式の関数オブジェクトも可。演算/コピーはO(1)。
// 点添字は0<=p<size()、区間は0<=l<=r<=size()の半開区間。
// set(int p,S x): 点代入、O(log(n+1))。get(int p): 点のS値、O(1)。prod(int l,int r): 左からの区間積、O(log(n+1))。
// all_prod(): 全積のS値、O(1)。空区間・空列の積はe()。積は非可換でもよい。
// max_right<pred>(int l)/min_left<pred>(int r): bool pred(S)を使う境界探索。述語を第2引数に渡す形式も可。戻り値はint、O(log(n+1))。
// 探索はpred(e())==trueで、区間を延ばすと真から偽へ一度だけ変化すること。述語に副作用を持たせない。
// [追加機能]
// size()/empty(): intの要素数/空か、O(1)。transform(int p,f): 点をf(現在値)へ更新、O(log(n+1))。
// values(): 列のコピー、O(n+1)。assign(vector<S>)/reset(int n)/reset(): 列/n個/現在の長さの単位元へ再構築、O(旧n+n+1)。
// clear()/swap(other): 容量を保持して空へ/交換、O(旧n+1)/O(1)。コピーは独立、移動元は空。値の演算等が投げる場合は内容の強い保証なし。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <bit>
#include <cstddef>
#include <functional>
#include <limits>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
#include <array>
#include <span>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_HLD_SEGMENT_ACCESS_FORWARD_DEFINED
#define SIRKIT_HLD_SEGMENT_ACCESS_FORWARD_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ { template<class Range> struct HldSegmentAccess; }
#endif
#ifndef SIRKIT_SEGMENT_ARRAY_CAPACITY_DEFINED
#define SIRKIT_SEGMENT_ARRAY_CAPACITY_DEFINED
namespace detail {
inline std::size_t CheckedSegmentLeafBase(std::size_t count, std::size_t limit, const char* error) {
if (count == 0) return 1;
if (count > std::bit_floor(limit)) throw std::length_error(error);
return std::bit_ceil(count);
}
inline int CheckedSegmentArrayCount(std::size_t count, const char* error) {
if (count > static_cast<std::size_t>(std::numeric_limits<int>::max())) throw std::length_error(error);
return static_cast<int>(count);
}
}
#endif
#ifndef SIRKIT_SEGMENT_TREE_DEFINED
#define SIRKIT_SEGMENT_TREE_DEFINED
template<class S, auto op, auto e>
class segtree {
static_assert(std::is_invocable_r_v<S, decltype(op), S, S>, "segtree: op(S,S) must return S");
static_assert(std::is_invocable_r_v<S, decltype(e)>, "segtree: e() must return S");
using HldSegmentTag = void;
template<class> friend struct /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::HldSegmentAccess;
S identity_;
std::size_t n_ = 0, base_ = 1;
std::vector<S> data_;
static std::size_t leaf_base(std::size_t n) {
return detail::CheckedSegmentLeafBase(n, std::vector<S>{}.max_size() / 2, "segtree: size");
}
static std::size_t checked_size(int n) {
#ifndef SKIP_RUNTIME_CHECKS
if (n < 0) throw std::invalid_argument("segtree: negative size");
#endif
return static_cast<std::size_t>(n);
}
static int vector_size(const std::vector<S>& values) {
return detail::CheckedSegmentArrayCount(values.size(), "segtree: int size overflow");
}
void check_index(int i) const {
#ifndef SKIP_RUNTIME_CHECKS
if (i < 0 || static_cast<std::size_t>(i) >= n_) throw std::out_of_range("segtree: index");
#else
(void)i;
#endif
}
void check_range(int l, int r) const {
#ifndef SKIP_RUNTIME_CHECKS
if (l < 0 || l > r || static_cast<std::size_t>(r) > n_) throw std::out_of_range("segtree: range");
#else
(void)l; (void)r;
#endif
}
static unsigned aligned_node(unsigned value) {
if (value == 0) std::unreachable();
return value >> std::countr_zero(value);
}
void rebuild() {
for (auto p = base_; p > 1;) {
--p;
data_[p] = std::invoke(op, data_[2 * p], data_[2 * p + 1]);
}
}
void update_carried_ancestors(std::size_t p) {
if (p <= 1) return;
S value = std::as_const(data_)[p];
while (p > 1) {
const S sibling = std::as_const(data_)[p ^ 1];
const S left = (p & 1) ? sibling : value;
const S right = (p & 1) ? value : sibling;
value = std::invoke(op, left, right);
p >>= 1;
data_[p] = std::as_const(value);
}
}
void update_ancestors(std::size_t p) {
if constexpr (std::is_trivially_copyable_v<S> && std::is_copy_constructible_v<S> &&
std::is_copy_assignable_v<S> && sizeof(S) <= 16 &&
std::is_invocable_r_v<S, decltype(op), const S&, const S&>) {
#if defined(__clang__)
if constexpr (sizeof(S) > 8) {
// 照会を含む呼び出し側のコードが膨らむのを抑える。
[[clang::noinline]] update_carried_ancestors(p);
return;
}
#endif
update_carried_ancestors(p);
} else {
for (p >>= 1; p; p >>= 1) data_[p] = std::invoke(op, data_[2 * p], data_[2 * p + 1]);
}
}
public:
segtree() : segtree(0) {}
explicit segtree(int n)
: identity_(std::invoke(e)), n_(checked_size(n)), base_(leaf_base(n_)),
data_(n_ ? 2 * base_ : 0, identity_) {}
explicit segtree(const std::vector<S>& values) : segtree(vector_size(values)) {
if (!n_) return;
std::copy(values.begin(), values.end(), data_.begin() + base_);
rebuild();
}
segtree(const segtree&) = default;
segtree& operator=(const segtree& other) {
if (this != &other) { segtree replacement(other); swap(replacement); }
return *this;
}
segtree(segtree&& other)
: identity_(other.identity_), n_(other.n_), base_(other.base_), data_(std::move(other.data_)) {
other.n_ = 0; other.base_ = 1; other.data_.clear();
}
segtree& operator=(segtree&& other) {
if (this != &other) { segtree replacement(std::move(other)); swap(replacement); }
return *this;
}
int size() const noexcept { return static_cast<int>(n_); }
bool empty() const noexcept { return n_ == 0; }
S get(int i) const { check_index(i); return data_[base_ + static_cast<std::size_t>(i)]; }
void set(int i, S value) {
check_index(i);
const auto p = base_ + static_cast<std::size_t>(i);
data_[p] = std::move(value);
update_ancestors(p);
}
template<class F> void transform(int i, F&& f) {
check_index(i);
const auto p = base_ + static_cast<std::size_t>(i);
data_[p] = std::invoke(std::forward<F>(f), std::as_const(data_)[p]);
update_ancestors(p);
}
S prod(int l, int r) const {
check_range(l, r);
if (l == r) return identity_;
// n<=INT_MAXなので葉番号はunsignedに収まり、両端は常に正。
unsigned first = static_cast<unsigned>(base_) + static_cast<unsigned>(l);
unsigned last = static_cast<unsigned>(base_) + static_cast<unsigned>(r);
auto step = first & (~first + 1);
if (step > last - first) {
// firstの整列幅より残りが短ければ、右端の下位bitを落としてfirstへ戻れる。
S result = data_[aligned_node(last) - 1];
last -= last & (~last + 1);
while (first < last) {
result = std::invoke(op, data_[aligned_node(last) - 1], result);
last -= last & (~last + 1);
}
return result;
}
// 左から最大の整列ブロックを選ぶ。最初は節点をコピーし、単位元との積を省く。
S left = data_[aligned_node(first)];
first += step;
if (first == last) return left;
// 短い残区間では分割点の計算を省く。
if (last - first <= 32) {
while (first < last && (step = first & (~first + 1)) <= last - first) {
left = std::invoke(op, left, data_[aligned_node(first)]);
first += step;
}
if (first == last) return left;
S right = data_[aligned_node(last) - 1];
last -= last & (~last + 1);
while (first < last) {
right = std::invoke(op, data_[aligned_node(last) - 1], right);
last -= last & (~last + 1);
}
return std::invoke(op, left, right);
}
// 左走査が止まる整列境界を先に求め、独立な左右の積を交互に進める。
const unsigned stop = last & (0U - std::bit_floor((first - 1) ^ (last - 1)));
if (stop == last) {
while (first < stop) {
left = std::invoke(op, left, data_[aligned_node(first)]);
first += first & (~first + 1);
}
return left;
}
S right = data_[aligned_node(last) - 1];
last -= last & (~last + 1);
while (first < stop && last > stop) {
left = std::invoke(op, left, data_[aligned_node(first)]);
first += first & (~first + 1);
right = std::invoke(op, data_[aligned_node(last) - 1], right);
last -= last & (~last + 1);
}
while (first < stop) {
left = std::invoke(op, left, data_[aligned_node(first)]);
first += first & (~first + 1);
}
while (last > stop) {
right = std::invoke(op, data_[aligned_node(last) - 1], right);
last -= last & (~last + 1);
}
return std::invoke(op, left, right);
}
S all_prod() const { return n_ ? data_[1] : identity_; }
template<bool (*Pred)(S)> int max_right(int l) const { return max_right(l, Pred); }
template<class Pred> int max_right(int l, Pred pred) const {
check_range(l, l);
#ifndef SKIP_RUNTIME_CHECKS
if (!std::invoke(pred, identity_)) throw std::invalid_argument("segtree: predicate(e())");
#endif
if (static_cast<std::size_t>(l) == n_) return size();
S accumulated = identity_;
auto node = base_ + static_cast<std::size_t>(l);
while (true) {
while (!(node & 1)) node >>= 1;
S candidate = std::invoke(op, accumulated, data_[node]);
if (!std::invoke(pred, candidate)) {
while (node < base_) {
node *= 2;
S next = std::invoke(op, accumulated, data_[node]);
if (std::invoke(pred, next)) { accumulated = std::move(next); ++node; }
}
return static_cast<int>(std::min(n_, node - base_));
}
accumulated = std::move(candidate);
++node;
if ((node & (node - 1)) == 0) return size();
}
}
template<bool (*Pred)(S)> int min_left(int r) const { return min_left(r, Pred); }
template<class Pred> int min_left(int r, Pred pred) const {
check_range(r, r);
#ifndef SKIP_RUNTIME_CHECKS
if (!std::invoke(pred, identity_)) throw std::invalid_argument("segtree: predicate(e())");
#endif
if (r == 0) return 0;
S accumulated = identity_;
auto node = base_ + static_cast<std::size_t>(r);
while (true) {
--node;
while (node > 1 && (node & 1)) node >>= 1;
S candidate = std::invoke(op, data_[node], accumulated);
if (!std::invoke(pred, candidate)) {
while (node < base_) {
node = 2 * node + 1;
S next = std::invoke(op, data_[node], accumulated);
if (std::invoke(pred, next)) { accumulated = std::move(next); --node; }
}
return static_cast<int>(node + 1 - base_);
}
accumulated = std::move(candidate);
if ((node & (node - 1)) == 0) return 0;
}
}
std::vector<S> values() const {
if (!n_) return {};
return std::vector<S>(data_.begin() + base_, data_.begin() + base_ + n_);
}
void assign(const std::vector<S>& values) { segtree replacement(values); swap(replacement); }
void reset(int n) { segtree replacement(n); swap(replacement); }
void reset() { std::fill(data_.begin(), data_.end(), identity_); }
void clear() noexcept { data_.clear(); n_ = 0; base_ = 1; }
void swap(segtree& other) noexcept(std::is_nothrow_swappable_v<S>) {
using std::swap;
swap(identity_, other.identity_);
swap(n_, other.n_); swap(base_, other.base_); data_.swap(other.data_);
}
};
#endif
#ifndef SIRKIT_RANGE_NONDECREASING_SUBSEQUENCE_DEFINED
#define SIRKIT_RANGE_NONDECREASING_SUBSEQUENCE_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/
{
template <std::size_t Alphabet>
struct MonotoneSubsequenceSummary
{
std::array<int, Alphabet * (Alphabet + 1) / 2> lengths{};
static constexpr std::size_t index(std::size_t low, std::size_t high) noexcept
{
return high * (high + 1) / 2 + low;
}
[[nodiscard]] constexpr int get(std::size_t low, std::size_t high) const noexcept
{
return lengths[index(low, high)];
}
};
template <std::size_t Alphabet>
constexpr MonotoneSubsequenceSummary<Alphabet> EmptyMonotoneSubsequence() noexcept
{
return {};
}
template <std::size_t Alphabet>
constexpr MonotoneSubsequenceSummary<Alphabet> SingleMonotoneSubsequence(std::size_t symbol) noexcept
{
MonotoneSubsequenceSummary<Alphabet> result{};
for (std::size_t high = symbol; high < Alphabet; ++high)
{
for (std::size_t low = 0; low <= symbol; ++low)
{
result.lengths[result.index(low, high)] = 1;
}
}
return result;
}
template <std::size_t Alphabet>
constexpr MonotoneSubsequenceSummary<Alphabet> JoinMonotoneSubsequences(
const MonotoneSubsequenceSummary<Alphabet> &left, const MonotoneSubsequenceSummary<Alphabet> &right) noexcept
{
MonotoneSubsequenceSummary<Alphabet> result{};
for (std::size_t high = 0; high < Alphabet; ++high)
{
for (std::size_t low = 0; low <= high; ++low)
{
// 境界値cutを共有し、前半はcut以下、後半はcut以上の値を選ぶ。
auto best = left.get(low, low) + right.get(low, high);
for (std::size_t cut = low + 1; cut <= high; ++cut)
{
best = std::max(best, left.get(low, cut) + right.get(cut, high));
}
result.lengths[result.index(low, high)] = best;
}
}
return result;
}
} // namespace reinsirk::detail
template <std::size_t Alphabet>
requires (1 <= Alphabet && Alphabet <= 256)
class RangeNondecreasingSubsequence
{
using Summary = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::MonotoneSubsequenceSummary<Alphabet>;
using Tree = segtree<Summary, /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::JoinMonotoneSubsequences<Alphabet>, /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::EmptyMonotoneSubsequence<Alphabet>>;
Tree tree_;
static void check_symbol([[maybe_unused]] int symbol)
{
#ifndef SKIP_RUNTIME_CHECKS
if (symbol < 0 || symbol >= static_cast<int>(Alphabet))
{
throw std::out_of_range("RangeNondecreasingSubsequence: symbol");
}
#endif
}
static Summary leaf(int symbol)
{
check_symbol(symbol);
return /*SIRKIT_NS_REWRITE_V1:R:OjpyZWluc2lyazo6ZGV0YWls*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::SingleMonotoneSubsequence<Alphabet>(static_cast<std::size_t>(symbol));
}
static std::vector<Summary> build(std::span<const int> symbols)
{
static_cast<void>(/*SIRKIT_NS_REWRITE_V1:R:OjpyZWluc2lyazo6ZGV0YWls*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::CheckedSegmentArrayCount(symbols.size(), "RangeNondecreasingSubsequence: size"));
std::vector<Summary> nodes;
nodes.reserve(symbols.size());
for (const auto symbol : symbols)
{
nodes.push_back(leaf(symbol));
}
return nodes;
}
public:
RangeNondecreasingSubsequence() = default;
explicit RangeNondecreasingSubsequence(std::span<const int> symbols) : tree_(build(symbols))
{
}
[[nodiscard]] int size() const noexcept
{
return tree_.size();
}
[[nodiscard]] bool empty() const noexcept
{
return tree_.empty();
}
void set(int position, int symbol)
{
tree_.set(position, leaf(symbol));
}
[[nodiscard]] int longest(int left, int right) const
{
return tree_.prod(left, right).get(0, Alphabet - 1);
}
[[nodiscard]] int longest(int left, int right, int low, int high) const
{
#ifndef SKIP_RUNTIME_CHECKS
check_symbol(low);
check_symbol(high);
if (low > high)
{
throw std::invalid_argument("RangeNondecreasingSubsequence: symbol interval");
}
#endif
return tree_.prod(left, right).get(static_cast<std::size_t>(low), static_cast<std::size_t>(high));
}
[[nodiscard]] int replacement_count(int left, int right) const
{
const auto keep = longest(left, right);
return right - left - keep;
}
[[nodiscard]] int all() const
{
return tree_.all_prod().get(0, Alphabet - 1);
}
};
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1