sirkit-cpp-library

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

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

桁DP

Algorithm/Digit_DP.cpp · ソース · 文書 Last Commit

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

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

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

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

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

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

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

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

桁を左から読み、決めた規則で状態を変えます。上限以下の数を、読み終えたときの状態ごとに数えます。

digit_dp_counts<Count>(upper, state_count, initial, transition, radix)

upper は2〜36進数の文字列です。radix の既定は10です。0 から upper までを含めて数えます。状態番号は [0,state_count) で、initial から始めます。

transition(state,digit,leading_zero) は次の状態番号を返します。その桁を選ばせない場合は std::nullopt を返せます。leading_zero は先頭に並ぶ0だけ真です。数0では全桁が先頭の0です。

Count{} は0、Count{1} は1で、+= を使える型を指定します。加算と遷移が $O(1)$ なら、桁数 $L$、状態数 $S$、基数 $B$ として $O((L+1)SB)$ 時間、$O(SB)$ 領域です。

const auto count = sirkit::digit_dp_counts<std::uint64_t>("25", 2, 0,
    [](std::size_t seen, unsigned digit, bool leading_zero) {
        return seen || (digit == 0 && !leading_zero);
    });
// 先頭の0を除き、0を含むのは10と20。count[1] == 2。

使用例 / Verify

ソースのAPI注記
digit_dp_counts<Count>(upper,states,initial,transition,radix=10): 0以上upper以下の数を、最終状態別に数える。
upperは2..36進数の非空文字列。状態は[0,states)。初期状態はinitial。
transition(state,digit,leading_zero): 次状態またはnullopt。leading_zeroは先頭の0に限りtrue。
Count{}は0、Count{1}は1。加算できること。桁数LでO((L+1)states*radix)時間・O(states*radix)領域。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
S - Digit Sum digit_dp_dp_s.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/digit_dp.md
// 参考(Verify問題): https://atcoder.jp/contests/dp/tasks/dp_s
//
// API一覧
// digit_dp_counts<Count>(upper,states,initial,transition,radix=10): 0以上upper以下の数を、最終状態別に数える。
// upperは2..36進数の非空文字列。状態は[0,states)。初期状態はinitial。
// transition(state,digit,leading_zero): 次状態またはnullopt。leading_zeroは先頭の0に限りtrue。
// Count{}は0、Count{1}は1。加算できること。桁数LでO((L+1)states*radix)時間・O(states*radix)領域。


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


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_DIGIT_DP_DEFINED
#define SIRKIT_DIGIT_DP_DEFINED
namespace detail
{
inline unsigned DecodeDigitDP(char character) noexcept
{
    if (character >= '0' && character <= '9')
    {
        return static_cast<unsigned>(character - '0');
    }
    if (character >= 'A' && character <= 'Z')
    {
        return static_cast<unsigned>(character - 'A' + 10);
    }
    if (character >= 'a' && character <= 'z')
    {
        return static_cast<unsigned>(character - 'a' + 10);
    }
    return 36;
}
}

template <class Count, class Transition>
std::vector<Count> digit_dp_counts(std::string_view upper, std::size_t state_count,
                                   std::size_t initial, const Transition &transition, unsigned radix = 10)
{
#ifndef SKIP_RUNTIME_CHECKS
    if (upper.empty() || initial >= state_count || radix < 2 || radix > 36)
    {
        throw std::invalid_argument("digit_dp_counts: invalid upper bound, initial state or radix");
    }
#endif
    std::vector<Count> below, next;
    std::vector<std::size_t> table;
    const auto max_states = std::min(below.max_size() / 2, table.max_size() / (2 * radix));
    if (state_count > max_states)
    {
        throw std::length_error("digit_dp_counts: state table capacity");
    }
    const auto slots = 2 * state_count;
    table.resize(slots * radix, slots);
    below.resize(slots);
    next.resize(slots);
    // 上側のstates個は、すでに0以外の桁を読んだ状態を持つ。
    for (std::size_t slot = 0; slot < slots; ++slot)
    {
        const bool unstarted = slot < state_count;
        const auto state = unstarted ? slot : slot - state_count;
        for (unsigned digit = 0; digit < radix; ++digit)
        {
            const bool leading_zero = unstarted && digit == 0;
            const std::optional<std::size_t> destination = transition(state, digit, leading_zero);
            if (destination)
            {
#ifndef SKIP_RUNTIME_CHECKS
                if (*destination >= state_count)
                {
                    throw std::out_of_range("digit_dp_counts: transition state");
                }
#endif
                table[slot * radix + digit] = *destination + (leading_zero ? 0 : state_count);
            }
        }
    }
    const auto add_below = [&](std::size_t slot, const Count &value)
    {
        if (slot != slots)
        {
            next[slot] += value;
        }
    };
    const Count one{1};
    std::size_t tight = initial;
    for (const char character : upper)
    {
        const auto limit = detail::DecodeDigitDP(character);
#ifndef SKIP_RUNTIME_CHECKS
        if (limit >= radix)
        {
            throw std::invalid_argument("digit_dp_counts: digit outside radix");
        }
#endif
        std::ranges::fill(next, Count{});
        for (std::size_t slot = 0; slot < slots; ++slot)
        {
            for (unsigned digit = 0; digit < radix; ++digit)
            {
                add_below(table[slot * radix + digit], below[slot]);
            }
        }
        // 上限と一致する接頭辞は一つなので、個数を持たず状態だけを追う。
        if (tight != slots)
        {
            for (unsigned digit = 0; digit < limit; ++digit)
            {
                add_below(table[tight * radix + digit], one);
            }
            tight = table[tight * radix + limit];
        }
        below.swap(next);
    }
    if (tight != slots)
    {
        below[tight] += one;
    }
    for (std::size_t state = 0; state < state_count; ++state)
    {
        below[state] += below[state + state_count];
    }
    below.resize(state_count);
    return below;
}
#endif

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