sirkit-cpp-library

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

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

個数制限付きナップサック

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

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

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

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

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

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

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

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

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

各品目の重さ・価値・個数上限を指定し、選んだ品目の価値を最大にします。

const std::vector<sirkit::KnapsackItem> items{{2, 3, 3}, {5, 8}};
auto best = sirkit::maximize_knapsack(7, items);  // 11

KnapsackItem

struct KnapsackItem {
    std::size_t weight;
    std::int64_t value;
    std::size_t count = 1;
};

重さ・価値・個数上限です。価値は非負とし、重さ0と個数上限0も指定できます。各品目を1個まで選べる場合は count を省略します。途中で作れる選択の価値の総和が符号付き64ビットを超えると std::overflow_error です。

maximize_knapsack

std::int64_t maximize_knapsack(std::size_t capacity, std::span<const KnapsackItem> items);

合計重量が capacity 以下になる選び方のうち、最大の価値を返します。 品目数 $n$、指定重量 $W$ に対して $O((n+1)(W+1))$ 時間・$O(W+1)$ 領域です。

maximize_exact_knapsack

std::optional<std::int64_t> maximize_exact_knapsack(
    std::size_t target, std::span<const KnapsackItem> items);

合計重量がちょうど target になる選び方のうち、最大の価値を返します。選び方がなければ std::nullopt です。 品目数 $n$、指定重量 $W$ に対して $O((n+1)(W+1))$ 時間・$O(W+1)$ 領域です。

使用例 / Verify

ソースのAPI注記
KnapsackItem {weight, value, count=1}: 重さ、非負の価値、選べる個数の上限。重さ0も可。
maximize_knapsack(capacity,items): 合計重量capacity以下の最大価値を返す。
maximize_exact_knapsack(target,items): 合計重量targetの最大価値。作れなければnullopt。
途中で作れる選択の価値の総和はint64_tに収める。超過はoverflow_error。
容量Wと品目数nに対して両方ともO((n+1)(W+1))時間・O(W+1)領域。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
D - Knapsack 1 knapsack_01.cpp 未提出 —
D - Choosing Souvenirs knapsack_bounded_exact.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/knapsack.md
//
// API一覧
// KnapsackItem {weight, value, count=1}: 重さ、非負の価値、選べる個数の上限。重さ0も可。
// maximize_knapsack(capacity,items): 合計重量capacity以下の最大価値を返す。
// maximize_exact_knapsack(target,items): 合計重量targetの最大価値。作れなければnullopt。
// 途中で作れる選択の価値の総和はint64_tに収める。超過はoverflow_error。
// 容量Wと品目数nに対して両方ともO((n+1)(W+1))時間・O(W+1)領域。

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

// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_KNAPSACK_DEFINED
#define SIRKIT_KNAPSACK_DEFINED
struct KnapsackItem
{
    std::size_t weight = 0;
    std::int64_t value = 0;
    std::size_t count = 1;
};

namespace detail
{
inline std::int64_t KnapsackAdd(std::int64_t base, std::int64_t value, std::size_t count)
{
    if (value == 0)
    {
        return base;
    }
    if (count > static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max() - base) / value))
    {
        throw std::overflow_error("knapsack: value does not fit in int64_t");
    }
    return base + static_cast<std::int64_t>(count) * value;
}

inline std::optional<std::int64_t> SolveKnapsack(std::size_t capacity, std::span<const KnapsackItem> items, bool exact)
{
    if (capacity >= std::vector<std::int64_t>().max_size())
    {
        throw std::length_error("knapsack: capacity exceeds storage limit");
    }
    std::int64_t zero_weight = 0;
    for (const auto &[weight, value, count] : items)
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (value < 0)
        {
            throw std::invalid_argument("knapsack: value must be nonnegative");
        }
#endif
        if (weight == 0)
        {
            zero_weight = KnapsackAdd(zero_weight, value, count);
        }
    }
    std::vector<std::int64_t> best(capacity + 1, exact ? -1 : zero_weight);
    best[0] = zero_weight;
    struct Candidate
    {
        std::size_t step;
        std::int64_t base;
    };
    std::vector<Candidate> queue;
    for (const auto &[weight, value, count] : items)
    {
        if (count == 0 || weight == 0 || weight > capacity)
        {
            continue;
        }
        const auto limit = capacity / weight;
        if (count == 1)
        {
            for (std::size_t i = capacity + 1; i > weight;)
            {
                --i;
                if (best[i - weight] >= 0)
                {
                    best[i] = std::max(best[i], KnapsackAdd(best[i - weight], value, 1));
                }
            }
            continue;
        }
        if (count >= limit)
        {
            for (std::size_t i = weight; i <= capacity; ++i)
            {
                if (best[i - weight] >= 0)
                {
                    best[i] = std::max(best[i], KnapsackAdd(best[i - weight], value, 1));
                }
            }
            continue;
        }

        // 重さの剰余が同じ位置だけを回る。候補は交差しないので、後から並ぶ弱い候補を除ける。
        queue.resize(limit + 1);
        for (std::size_t residue = 0; residue < weight; ++residue)
        {
            const auto last = (capacity - residue) / weight;
            std::size_t begin = 0, end = 0;
            for (std::size_t step = 0; step <= last; ++step)
            {
                const auto i = residue + step * weight;
                if (begin < end && step - queue[begin].step > count)
                {
                    ++begin;
                }
                if (best[i] >= 0)
                {
                    while (begin < end)
                    {
                        const auto &back = queue[end - 1];
                        if (KnapsackAdd(back.base, value, step - back.step) > best[i])
                        {
                            break;
                        }
                        --end;
                    }
                    queue[end++] = {step, best[i]};
                }
                if (begin < end)
                {
                    best[i] = KnapsackAdd(queue[begin].base, value, step - queue[begin].step);
                }
            }
        }
    }
    if (best[capacity] < 0)
    {
        return std::nullopt;
    }
    return best[capacity];
}
}

inline std::int64_t maximize_knapsack(std::size_t capacity, std::span<const KnapsackItem> items)
{
    return *detail::SolveKnapsack(capacity, items, false);
}

inline std::optional<std::int64_t> maximize_exact_knapsack(std::size_t target, std::span<const KnapsackItem> items)
{
    return detail::SolveKnapsack(target, items, true);
}
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1
Back to top page