ポテンシャル付き単一始点最短路(Johnson 法で使うダイクストラ)
lib/graph/shortest_path_potential.hpp
インクルード
#include "graph/shortest_path_potential.hpp"
関数
| 名前 | 説明 |
|---|---|
shortest_path_potential |
ポテンシャル付き単一始点最短路(Johnson 法で使うダイクストラ) |
依存するヘッダ(1)
-
グラフ表現 (list_graph / csr_graph)
lib/graph/graph.hpp
実装
#pragma once
#include <functional>
#include <limits>
#include <queue>
#include <vector>
#include "graph/graph.hpp"
/// @brief ポテンシャル付き単一始点最短路(Johnson 法で使うダイクストラ)
/// @tparam G 重み付きグラフ型(`list_graph<T>` / `csr_graph<T>` のいずれでも可)
/// @note ポテンシャルで辺重みを非負化してからダイクストラを回し、最後に補正を戻す。
/// @complexity $O((V+E)\log V)$
template <weighted_graph_type G, class U, class T = graph_weight_t<G>>
std::vector<T> shortest_path_potential(const G &g, const std::vector<U> &potentials, int s = 0,
T inf = std::numeric_limits<T>::max()) {
struct _node {
constexpr _node() : _to(), _dist() {}
constexpr _node(int to, T dist) : _to(to), _dist(dist) {}
constexpr bool operator<(const _node &rhs) const { return this->dist() < rhs.dist(); }
constexpr bool operator>(const _node &rhs) const { return rhs < *this; }
constexpr int to() const { return this->_to; }
constexpr T dist() const { return this->_dist; }
private:
int _to;
T _dist;
};
int n = g.size();
std::vector<T> dists(n, inf);
std::priority_queue<_node, std::vector<_node>, std::greater<>> p_que;
dists[s] = T();
p_que.emplace(s, T());
while (!p_que.empty()) {
auto node = p_que.top();
p_que.pop();
if (dists[node.to()] < node.dist()) continue;
for (auto &e : g[node.to()]) {
auto next_dist = node.dist() + e.weight() + potentials[node.to()] - potentials[e.to()];
if (next_dist < dists[e.to()]) {
dists[e.to()] = next_dist;
p_que.emplace(e.to(), next_dist);
}
}
}
for (int i = 0; i < n; ++i) dists[i] += potentials[i] - potentials[s];
return dists;
}