競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
負の重みを含む疎な有向グラフで、全点対の最短距離を求めます。各始点からの距離を 1 行ずつ受け取れるので、合計だけ必要なら全行を保持せずに使えます。
for_each_johnson_distance_row(n, edges, on_row) に頂点数、辺の列、行を受け取る関数を渡します。辺は JohnsonEdge{from, to, weight} です。頂点は 0 始まりで、重みの絶対値は INT64_MAX / (4 * max(1, n)) 以下です。
on_row(source, row) に始点番号と、頂点順の距離の span が渡ります。距離は int64_t で、未到達は nullopt です。行を後から使う場合はコピーしてください。負閉路があれば false が返り、行は渡されません。処理できれば true が返ります。
辺数を m とすると、コールバックを除き O(n(n + m log(m + 1))) 時間、O(n + m) 領域です。
使用例 · 行合計の Verify · 負閉路と距離行列の Verify · Johnson の論文
JohnsonEdge{from,to,weight}: 0始まりの端点と int64_t の重み。自己辺・多重辺可。
for_each_johnson_distance_row(n,edges,on_row): 全点対の最短距離を始点順に1行ずつ渡す。
on_row(source, span<const optional<int64_t>>) の span は呼び出し中だけ有効。未到達はnullopt。
負閉路があれば on_row を呼ばず false。それ以外は true。
重みの絶対値は INT64_MAX/(4 max(1,n)) 以下。負辺可。
時間 O(n(n+m log(m+1)))(コールバックを除く)、追加領域 O(n+m)。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Typical Shortest Path Sum | johnson_shortest_paths.cpp | 未提出 | — |
| All Pairs Shortest Path | johnson_shortest_paths_matrix.cpp | 未提出 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// 参考(Johnson 法): https://doi.org/10.1145/321992.321993
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/johnson_shortest_paths.md
//
// API一覧
// JohnsonEdge{from,to,weight}: 0始まりの端点と int64_t の重み。自己辺・多重辺可。
// for_each_johnson_distance_row(n,edges,on_row): 全点対の最短距離を始点順に1行ずつ渡す。
// on_row(source, span<const optional<int64_t>>) の span は呼び出し中だけ有効。未到達はnullopt。
// 負閉路があれば on_row を呼ばず false。それ以外は true。
// 重みの絶対値は INT64_MAX/(4 max(1,n)) 以下。負辺可。
// 時間 O(n(n+m log(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_JOHNSON_SHORTEST_PATHS_DEFINED
#define SIRKIT_JOHNSON_SHORTEST_PATHS_DEFINED
struct JohnsonEdge
{
int from;
int to;
std::int64_t weight;
};
template <typename Consumer>
bool for_each_johnson_distance_row(int n, std::span<const JohnsonEdge> edges, Consumer &&on_row)
{
#ifndef SKIP_RUNTIME_CHECKS
if (n < 0)
{
throw std::length_error("for_each_johnson_distance_row: negative vertex count");
}
const auto cap = (std::numeric_limits<std::int64_t>::max() / 4) / std::max(1, n);
#endif
bool needs_potentials = false;
for (const auto &[u, v, weight] : edges)
{
#ifndef SKIP_RUNTIME_CHECKS
if (u < 0 || u >= n || v < 0 || v >= n)
{
throw std::out_of_range("for_each_johnson_distance_row: invalid endpoint");
}
if (weight < -cap || weight > cap)
{
throw std::out_of_range("for_each_johnson_distance_row: weight too large for the vertex count");
}
#endif
needs_potentials = needs_potentials || weight < 0;
}
// 全頂点に重み0で届く仮の始点を、初期値0で表す。
std::vector<std::int64_t> potential(n);
if (needs_potentials)
{
std::vector<std::int64_t> next(n);
for (int remaining = n;; --remaining)
{
next = potential;
bool improved = false;
for (const auto &[u, v, weight] : edges)
{
const auto candidate = potential[u] + weight;
if (candidate < next[v])
{
next[v] = candidate;
improved = true;
}
}
if (!improved)
{
break;
}
if (remaining == 1)
{
return false;
}
potential.swap(next);
}
}
detail::ShortestPathAdjacency graph(n);
for (const auto &[u, v, weight] : edges)
{
const auto nonnegative = weight + potential[u] - potential[v];
graph[u].emplace_back(static_cast<std::uint64_t>(nonnegative), v);
}
std::vector<std::optional<std::int64_t>> row(n);
for (int u = 0; u < n; ++u)
{
const auto reweighted = detail::shortest_path_edge_distances(graph, u);
for (int v = 0; v < n; ++v)
{
if (reweighted[v])
{
row[v] = static_cast<std::int64_t>(*reweighted[v]) - potential[u] + potential[v];
}
else
{
row[v] = std::nullopt;
}
}
std::invoke(on_row, u, std::span<const std::optional<std::int64_t>>(row));
}
return true;
}
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1