sirkit-cpp-library

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

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

最短路で使う辺

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

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

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

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

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

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

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

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

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

始点から終点への最短路を考え、各辺を通る最短路があるか、すべての最短路がその辺を通るかを調べます。本体

shortest_path_edge_usage

ShortestPathEdgeUsage shortest_path_edge_usage(
    int n, std::span<const ShortestPathEdge> edges,
    int source, int target, bool undirected = false);

ShortestPathEdge{from, to, weight} の頂点番号は $0$ 始まりで、重みは正の std::uint64_t です。無向グラフには undirected = true を指定し、各辺を一度だけ渡します。

  • distance は最短距離です。到達不能、または距離が std::uint64_t の上限を超える場合は std::nullopt を返します。
  • edge_use[i] は入力の辺 $i$ の判定です。通る最短路がなければ none、一部の最短路が通れば some、すべてが通れば all です。ShortestPathEdgeUse で表します。

各最短路を始点からの距離に沿って見ると、辺の重みが正なので距離は増え続けます。最短路で使える辺がある距離をまたぐとき、ほかにその距離をまたぐ辺がなければ、その辺はすべての最短路に含まれます。逆にすべての最短路に含まれる辺では、その辺の両端の距離の間をまたげる辺がほかにありません。

頂点数 $n$、辺数 $m$ に対し $O((n+m)\log(n+m+1))$ 時間、$O(n+m)$ 領域です。

使用例

const std::array edges{sirkit::ShortestPathEdge{0, 1, 2},
                       sirkit::ShortestPathEdge{1, 2, 3},
                       sirkit::ShortestPathEdge{0, 2, 5}};
const auto routes = sirkit::shortest_path_edge_usage(3, edges, 0, 2);
// 距離は5。どの辺も一部の最短路だけが通るので、すべてsome。

使用例・Verify

ソースのAPI注記
[shortest_path_edge_usage]
shortest_path_edge_usage(n, edges, source, target, undirected=false):
  最短距離と、各辺を使う最短路が none / some / all のどれかを返す。
  頂点は0始まり。辺の長さは正のuint64_t。最短距離をuint64_tで表せなければnullopt。
  時間O((n+m)log(n+m+1))、領域O(n+m)。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Road Blocked 2 shortest_path_edge_usage.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/shortest_path_edge_usage.md
//
// API一覧
// [shortest_path_edge_usage]
// shortest_path_edge_usage(n, edges, source, target, undirected=false):
//   最短距離と、各辺を使う最短路が none / some / all のどれかを返す。
//   頂点は0始まり。辺の長さは正のuint64_t。最短距離をuint64_tで表せなければnullopt。
//   時間O((n+m)log(n+m+1))、領域O(n+m)。


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


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

struct ShortestPathEdge
{
    int from;
    int to;
    std::uint64_t weight;
};

namespace detail
{
using ShortestPathAdjacency = std::vector<std::vector<std::pair<std::uint64_t, int>>>;

inline std::vector<std::optional<std::uint64_t>> shortest_path_edge_distances(const ShortestPathAdjacency &graph, int source)
{
    using State = std::pair<std::uint64_t, int>;
    std::priority_queue<State, std::vector<State>, std::greater<State>> pending;
    std::vector<std::optional<std::uint64_t>> distance(graph.size());
    distance[source] = 0;
    pending.emplace(0, source);
    while (!pending.empty())
    {
        const auto [prefix, vertex] = pending.top();
        pending.pop();
        if (prefix != distance[vertex].value())
        {
            continue;
        }
        for (const auto &[weight, next] : graph[vertex])
        {
            if (weight > std::numeric_limits<std::uint64_t>::max() - prefix)
            {
                continue;
            }
            const std::uint64_t candidate = prefix + weight;
            if (!distance[next] || candidate < distance[next].value())
            {
                distance[next] = candidate;
                pending.emplace(candidate, next);
            }
        }
    }
    return distance;
}
} // namespace detail

#endif

#ifndef SIRKIT_SHORTEST_PATH_EDGE_USAGE_DEFINED
#define SIRKIT_SHORTEST_PATH_EDGE_USAGE_DEFINED

enum class ShortestPathEdgeUse : std::uint8_t
{
    none,
    some,
    all,
};

struct ShortestPathEdgeUsage
{
    std::optional<std::uint64_t> distance;
    std::vector<ShortestPathEdgeUse> edge_use;
};

inline ShortestPathEdgeUsage shortest_path_edge_usage(
    int n, std::span<const ShortestPathEdge> edges, int source, int target, bool undirected = false)
{
#ifndef SKIP_RUNTIME_CHECKS
    if (source < 0 || source >= n || target < 0 || target >= n)
    {
        throw std::out_of_range("shortest_path_edge_usage terminal");
    }
#endif
    detail::ShortestPathAdjacency graph(n);
    detail::ShortestPathAdjacency reverse(undirected ? 0 : n);
    for (const auto &[from, to, weight] : edges)
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (from < 0 || from >= n || to < 0 || to >= n)
        {
            throw std::out_of_range("shortest_path_edge_usage endpoint");
        }
        if (weight == 0)
        {
            throw std::invalid_argument("shortest_path_edge_usage weight must be positive");
        }
#endif
        graph[from].emplace_back(weight, to);
        if (undirected)
        {
            graph[to].emplace_back(weight, from);
        }
        else
        {
            reverse[to].emplace_back(weight, from);
        }
    }

    const auto from_source = detail::shortest_path_edge_distances(graph, source);
    ShortestPathEdgeUsage result{from_source[target], std::vector<ShortestPathEdgeUse>(edges.size())};
    if (!result.distance || source == target)
    {
        return result;
    }
    const auto to_target = detail::shortest_path_edge_distances(undirected ? graph : reverse, target);
    const auto distance = result.distance.value();
    struct Event
    {
        std::uint64_t position;
        std::size_t edge;
        bool starts;
    };
    std::vector<Event> events;
    auto add_events = [&](int from, int to, std::uint64_t weight, std::size_t id)
    {
        if (!from_source[from] || !to_target[to])
        {
            return;
        }
        const auto left = from_source[from].value();
        const auto suffix = to_target[to].value();
        if (left > distance || weight > distance - left || suffix != distance - left - weight)
        {
            return;
        }
        result.edge_use[id] = ShortestPathEdgeUse::some;
        events.push_back({left, id, true});
        events.push_back({left + weight, id, false});
    };
    for (std::size_t id = 0; id < edges.size(); ++id)
    {
        const auto &[from, to, weight] = edges[id];
        add_events(from, to, weight, id);
        if (undirected)
        {
            add_events(to, from, weight, id);
        }
    }
    std::ranges::sort(events, {}, &Event::position);
    std::size_t active_count = 0;
    std::size_t active_xor = 0;
    for (std::size_t i = 0; i < events.size();)
    {
        const std::uint64_t position = events[i].position;
        do
        {
            const auto &[point, id, starts] = events[i++];
            active_xor ^= id;
            if (starts)
            {
                ++active_count;
            }
            else
            {
                --active_count;
            }
        } while (i < events.size() && events[i].position == position);
        // Every shortest path crosses each distance between the two terminals.
        if (active_count == 1)
        {
            result.edge_use[active_xor] = ShortestPathEdgeUse::all;
        }
    }
    return result;
}

#endif

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