sirkit-cpp-library

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

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

資源制約付き最短路

Graph/Resource_Constrained_Paths.cpp · ソース · 文書 Last Commit

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

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

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

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

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

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

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

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

移動に資源を使い、途中で補充できる有向グラフの最短時間を求めます。残量が多く所要時間が短い状態があれば、同じ頂点でそれより不利な状態を省きます。

ResourceConstrainedPaths(n, edges, source, capacity, initial) に ResourcePathArc{from, to, spend, gain, time} を渡します。辺を通るには資源 spend が必要です。支払った後に gain を受け取り、補充と初期値は capacity で止まります。頂点番号は 0 始まりで、資源量と時間は uint64_t で、時間がその範囲に収まる経路を扱います。

  • minimum_time(v, required=0) は残量を required 以上にして到着する最短時間を返します。条件を満たせなければ nullopt です。
  • labels(v) は他の組に支配されない {remaining, time} を残量順に参照できます。

上限を C、辺数を m とすると、構築は最悪 O(n + (m+1)(C+1) log((m+1)(C+1)+2)) 時間、O((n+m)(C+1)) 領域です。最短時間の照会は頂点の組数を k として O(log(k+2)) です。

使用例 · Verify問題

ソースのAPI注記
ResourcePathArc{from,to,spend,gain,time}: 資源をspend消費しgain得る有向辺。timeは所要時間。
ResourceConstrainedPaths(n,edges,source,capacity,initial): 所持量が上限capacityの最短路を構築。
  初期値と補充は上限で止まる。資源がspend未満なら辺を通れない。頂点は0始まり。
  資源量・時間はuint64_t。時間が表現可能な経路だけ扱う。
minimum_time(v,required=0): 資源をrequired以上持って到着する最短時間。なければnullopt。O(log(k+2))。
labels(v): (残量,時間)のうち他の組に支配されないものを残量昇順で参照する。kはその組数。
  上限をCとし、最悪 O(n+(m+1)(C+1) log((m+1)(C+1)+2)) 時間、O((n+m)(C+1)) 領域。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
E - Two Currencies resource_constrained_paths.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/resource_constrained_paths.md
//
// API一覧
// ResourcePathArc{from,to,spend,gain,time}: 資源をspend消費しgain得る有向辺。timeは所要時間。
// ResourceConstrainedPaths(n,edges,source,capacity,initial): 所持量が上限capacityの最短路を構築。
//   初期値と補充は上限で止まる。資源がspend未満なら辺を通れない。頂点は0始まり。
//   資源量・時間はuint64_t。時間が表現可能な経路だけ扱う。
// minimum_time(v,required=0): 資源をrequired以上持って到着する最短時間。なければnullopt。O(log(k+2))。
// labels(v): (残量,時間)のうち他の組に支配されないものを残量昇順で参照する。kはその組数。
//   上限をCとし、最悪 O(n+(m+1)(C+1) log((m+1)(C+1)+2)) 時間、O((n+m)(C+1)) 領域。


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


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

struct ResourcePathArc
{
    int from;
    int to;
    std::uint64_t spend;
    std::uint64_t gain;
    std::uint64_t time;
};

struct ResourcePathLabel
{
    std::uint64_t remaining;
    std::uint64_t time;
};

class ResourceConstrainedPaths
{
public:
    ResourceConstrainedPaths(
        int n, std::span<const ResourcePathArc> edges, int source, std::uint64_t capacity, std::uint64_t initial)
    {
        if (n < 0)
        {
            throw std::length_error("ResourceConstrainedPaths: negative vertex count");
        }
        labels_.resize(n);
        check_vertex(source);

        std::vector<std::vector<std::size_t>> outgoing(n);
        for (std::size_t i = 0; i < edges.size(); ++i)
        {
            check_vertex(edges[i].from);
            check_vertex(edges[i].to);
            outgoing[edges[i].from].push_back(i);
        }

        using Key = std::tuple<std::uint64_t, std::uint64_t, int>;
        std::priority_queue<Key, std::vector<Key>, std::greater<Key>> pending;
        std::vector<std::map<std::uint64_t, std::uint64_t>> frontier(n);
        auto enqueue = [&](int v, std::uint64_t remaining, std::uint64_t time)
        {
            auto &labels = frontier[v];
            auto after = labels.lower_bound(remaining);
            if (after != labels.end())
            {
                if (after->second <= time)
                {
                    return;
                }
                if (after->first == remaining)
                {
                    after = labels.erase(after);
                }
            }
            auto first = after;
            while (first != labels.begin())
            {
                const auto before = std::prev(first);
                if (before->second < time)
                {
                    break;
                }
                first = before;
            }
            const auto hint = labels.erase(first, after);
            labels.emplace_hint(hint, remaining, time);
            pending.emplace(time, capacity - remaining, v);
        };
        enqueue(source, std::min(capacity, initial), 0);
        while (!pending.empty())
        {
            const auto [time, used, v] = pending.top();
            pending.pop();
            const auto remaining = capacity - used;
            const auto found = frontier[v].find(remaining);
            if (found == frontier[v].end() || found->second != time)
            {
                continue;
            }
            for (const auto id : outgoing[v])
            {
                const auto &edge = edges[id];
                if (remaining < edge.spend || edge.time > std::numeric_limits<std::uint64_t>::max() - time)
                {
                    continue;
                }
                const auto rest = remaining - edge.spend;
                const auto next = rest + std::min(edge.gain, capacity - rest);
                enqueue(edge.to, next, time + edge.time);
            }
        }

        for (int v = 0; v < n; ++v)
        {
            labels_[v].reserve(frontier[v].size());
            for (const auto &[remaining, time] : frontier[v])
            {
                labels_[v].push_back({remaining, time});
            }
        }
    }

    [[nodiscard]] std::span<const ResourcePathLabel> labels(int v) const
    {
        check_vertex(v);
        return labels_[v];
    }

    [[nodiscard]] std::optional<std::uint64_t> minimum_time(int v, std::uint64_t required = 0) const
    {
        const auto options = labels(v);
        const auto found = std::ranges::lower_bound(options, required, {}, &ResourcePathLabel::remaining);
        if (found == options.end())
        {
            return std::nullopt;
        }
        return found->time;
    }

private:
    void check_vertex([[maybe_unused]] int v) const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (static_cast<std::size_t>(v) >= labels_.size())
        {
            throw std::out_of_range("ResourceConstrainedPaths: invalid vertex");
        }
#endif
    }

    std::vector<std::vector<ResourcePathLabel>> labels_;
};

#endif

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