競技プログラミング用 C++ ライブラリ
components/dijkstra_topological.hpp · GitHub で見る
共通ページ
Dijkstra のトポロジカル前処理です。通常は graph/dijkstra.hpp を include し、dijkstra<true> または dijkstra_path<true> で有効にします。既定の dijkstra・dijkstra_path では使いません。
まず入次数が 0 の頂点から順に距離を確定し、残った部分を Dijkstra 法で探索します。有向閉路があるグラフにも使えます。DAG では優先度付きキューを使わず線形時間で処理します。
#include "lib/graph/dijkstra.hpp"
using I = std::int64_t;
std::vector<std::vector<std::pair<int, I>>> g(5);
g[0] = { {1, 4}, {2, 10} };
g[1] = { {2, 3} };
g[2] = { {3, 1} };
g[3] = { {2, 0}, {4, 2} };
auto distance = dijkstra<true>(g, 0); // {0,4,7,8,10}
auto [cost, path] = dijkstra_path<true>(g, 0, 4);
// cost = 10, path = {0,1,2,3,4}
全頂点の距離が必要なら dijkstra<true>、1 つの目的地までの距離と経路が必要なら dijkstra_path<true> を使います。隣接リストの辺は {行き先, 重み}、頂点番号は 0 始まりです。グラフは変更しません。グラフ全体の入次数を数えるため、閉路の多いグラフや一部だけ探索する場合には前処理のない dijkstra の方が軽くなることがあります。
| 操作 | 内容・返り値 | 計算量 |
|---|---|---|
dijkstra<true>(g,start) / dijkstra<true>(g,start,inf)
|
始点から全頂点への距離列。到達不能は T(-1)
|
DAG: \(O(n+m)\)、一般の 64 bit 以下の整数距離: \(O(n+mw)\)、その他: \(O(n+m\log m)\) |
dijkstra_path<true>(g,start,target) / dijkstra_path<true>(g,start,target,inf)
|
{最短距離, 頂点列}。頂点列は始点から目的地の順。到達不能は {T(-1),{}}
|
DAG: \(O(n+m)\)、一般の 64 bit 以下の整数距離: \(O(n+mw)\)、その他: \(O(n+m\log m)\) |
shortest_path_detail::topological_run<Path>(g,start,target,inf,parent) |
前処理付き探索の内部関数。到達不能の距離は inf のまま。Path=true では長さ \(n\) の parent に経路を保存し、目的地以外の距離は未確定の場合がある |
DAG: \(O(n+m)\)、一般の 64 bit 以下の整数距離: \(O(n+mw)\)、その他: \(O(n+m\log m)\) |
start == target の経路は {start}、距離は 0 です。複数の最短経路がある場合はそのうち 1 つを返します。重み 0 の辺・自己辺・多重辺に対応します。無向グラフでは各辺を両方向に追加しますが、入次数 0 の頂点が少なく前処理の効果は限られます。
inf は扱う距離より大きい正の値を指定します。既定値は \(\min(4\cdot 10^{18},\text{距離型の最大値})\) です。距離が inf 以上になる経路は扱いません。符号なし整数型の到達不能値 T(-1) はその型の最大値です。
入次数が 0 になった頂点は、その頂点に入る辺を持つ頂点が全て処理済みなので距離を確定できます。この除去を終えると、残った頂点から除去済みの頂点への辺はありません。確定済みの部分から残った部分へ渡した距離を初期値として、残った部分を Dijkstra 法で探索します。残る部分には閉路だけでなく、その下流の頂点も含まれます。
内部関数の g は size() と g[v] が使え、g[v] は {行き先, 重み} の範囲と empty() を持つ必要があります。全ての重みは非負とします。通常は公開関数を使います。
頂点数を \(n\)、辺数を \(m\)、距離型のビット数を \(w\le64\) とします。DAG では \(O(n+m)\) 時間、一般のグラフでは 64 bit 以下の整数距離に対して \(O(n+mw)\)、その他に対して \(O(n+m\log m)\) 時間です。追加空間は \(O(n+m)\) です。start == target の dijkstra_path<true> は \(O(1)\) 時間・空間です。
#ifndef DIJKSTRA_TOPOLOGICAL_HPP
#define DIJKSTRA_TOPOLOGICAL_HPP
#include "dijkstra_queue.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <limits>
#include <utility>
#include <vector>
namespace shortest_path_detail {
template<bool Path, class G, class T>
std::vector<T> topological_run(const G &g, int start, int target, T inf, std::vector<int> &parent) {
std::size_t n = std::size_t(g.size());
assert(n <= static_cast<std::size_t>(std::numeric_limits<int>::max()));
assert(start >= 0 && static_cast<std::size_t>(start) < n);
assert(inf > 0);
std::vector<T> distance(n, inf);
std::vector<std::size_t> indegree(n);
std::vector<int> ready;
ready.reserve(n);
for (std::size_t v = 0; v < n; ++v)
for (const auto &[to, weight] : g[int(v)]) {
assert(to >= 0 && static_cast<std::size_t>(to) < n);
assert(weight >= 0);
++indegree[to];
}
for (std::size_t v = 0; v < n; ++v)
if (!indegree[v]) ready.push_back(int(v));
distance[start] = 0;
auto improve = [&](int from, const T &cost, const T &allowance, int to, const auto &weight) {
if (reaches_limit(weight, allowance)) return false;
T next = cost + weight;
if (next >= distance[to]) return false;
if constexpr (Path) {
if (next >= distance[target]) return false;
parent[to] = from;
}
distance[to] = std::move(next);
return true;
};
for (std::size_t head = 0; head < ready.size(); ++head) {
int v = ready[head];
if constexpr (Path) if (v == target) return distance;
T cost = distance[v];
bool active = cost < inf;
if constexpr (Path) active &= cost < distance[target];
T allowance = active ? inf - cost : T(0);
for (const auto &[to, weight] : g[v]) {
if (active) improve(v, cost, allowance, to, weight);
if (--indegree[to] == 0) ready.push_back(to);
}
}
DistanceQueue<T> queue;
for (std::size_t v = 0; v < n; ++v) {
if (!indegree[v] || distance[v] == inf || g[v].empty()) continue;
if constexpr (Path) if (int(v) == target || distance[v] >= distance[target]) continue;
queue.push(distance[v], int(v));
}
while (!queue.empty()) {
const auto [cost, v] = queue.pop();
if (cost != distance[v]) continue;
if constexpr (Path) if (cost >= distance[target]) break;
T allowance = inf - cost;
for (const auto &[to, weight] : g[v]) {
if (!improve(v, cost, allowance, to, weight)) continue;
if constexpr (Path) if (to == target) continue;
if (!g[to].empty()) queue.push(distance[to], to);
}
}
return distance;
}
}
#endif
#line 1 "components/dijkstra_topological.hpp"
#line 1 "components/dijkstra_queue.hpp"
#line 1 "components/RadixHeap.hpp"
#include <algorithm>
#include <bit>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <type_traits>
#include <utility>
#include <vector>
template <class Key = std::uint64_t, class T = int>
class RadixHeap {
static_assert(std::is_integral_v<Key> && !std::is_same_v<Key, bool> && sizeof(Key) <= 8);
using U = std::make_unsigned_t<Key>;
using State = std::pair<Key, T>;
std::vector<State> bucket[std::numeric_limits<U>::digits + 1];
Key lower;
std::size_t count = 0;
int index(Key key) const { return std::bit_width(U(U(key) ^ U(lower))); }
void refill() {
assert(count);
if (!bucket[0].empty()) return;
int i = 1;
while (bucket[i].empty()) ++i;
lower = bucket[i][0].first;
for (const auto &s : bucket[i]) lower = std::min(lower, s.first);
for (auto &s : bucket[i]) bucket[index(s.first)].push_back(std::move(s));
bucket[i].clear();
}
public:
explicit RadixHeap(Key minimum = 0) : lower(minimum) {}
RadixHeap(const RadixHeap &) = default;
RadixHeap &operator=(const RadixHeap &) = default;
RadixHeap(RadixHeap &&other) noexcept : lower(other.lower), count(std::exchange(other.count, 0)) {
for (int i = 0; i <= std::numeric_limits<U>::digits; ++i) bucket[i] = std::move(other.bucket[i]);
}
RadixHeap &operator=(RadixHeap &&other) noexcept {
if (this != &other) {
lower = other.lower;
count = std::exchange(other.count, 0);
for (int i = 0; i <= std::numeric_limits<U>::digits; ++i) bucket[i] = std::move(other.bucket[i]);
}
return *this;
}
bool empty() const { return count == 0; }
std::size_t size() const { return count; }
Key last() const { return lower; }
void clear(Key minimum = 0) {
for (auto &b : bucket) b.clear();
lower = minimum;
count = 0;
}
void push(State s) {
assert(s.first >= lower);
bucket[index(s.first)].push_back(std::move(s));
++count;
}
const State &top() {
refill();
return bucket[0].back();
}
void pop() {
refill();
bucket[0].pop_back();
--count;
}
State pop_value() {
refill();
State s = std::move(bucket[0].back());
bucket[0].pop_back();
--count;
return s;
}
};
#line 10 "components/dijkstra_queue.hpp"
#include <functional>
#line 15 "components/dijkstra_queue.hpp"
namespace shortest_path_detail {
template<class Weight, class Distance>
bool reaches_limit(const Weight &weight, const Distance &limit) {
if constexpr (std::numeric_limits<Weight>::is_integer && std::numeric_limits<Weight>::is_bounded &&
std::numeric_limits<Distance>::is_integer && std::numeric_limits<Distance>::is_bounded) {
using Compare = std::common_type_t<Weight, Distance>;
return Compare(weight) >= Compare(limit);
} else return weight >= limit;
}
template<class T> class RadixQueue {
static_assert(std::is_integral_v<T> && sizeof(T) <= 8);
struct State { T key; int vertex; };
State small_[32];
std::vector<std::uint64_t> buckets_[33];
std::uint32_t minimum_[33];
std::uint32_t occupied_ = 0;
std::uint64_t last_ = 0;
std::size_t count_ = 0;
int mode_ = 0;
RadixHeap<std::uint64_t> wide_;
void put(std::uint64_t state) {
std::uint32_t key = state >> 32;
int index = std::bit_width(key ^ std::uint32_t(last_));
buckets_[index].push_back(state);
if (index) {
occupied_ |= std::uint32_t(1) << (index - 1);
minimum_[index] = std::min(minimum_[index], key);
}
}
void promote() {
if (mode_ == 0) {
for (std::size_t i = 0; i < count_; ++i) wide_.push({std::uint64_t(small_[i].key), small_[i].vertex});
} else {
for (auto &bucket : buckets_) {
for (auto state : bucket) {
std::uint64_t key = last_ + std::uint32_t(std::uint32_t(state >> 32) - std::uint32_t(last_));
wide_.push({key, int(std::uint32_t(state))});
}
bucket.clear();
}
}
mode_ = 2;
}
public:
bool empty() const { return count_ == 0; }
void push(T key, int vertex) {
assert(key >= 0 && std::uint64_t(key) >= last_);
if (mode_ == 0 && count_ < 32) {
small_[count_++] = {key, vertex};
return;
}
if (mode_ == 0) {
bool narrow = std::uint64_t(key) - last_ <= std::uint64_t(std::numeric_limits<std::int32_t>::max());
for (std::size_t i = 0; i < count_; ++i)
narrow &= std::uint64_t(small_[i].key) - last_ <= std::uint64_t(std::numeric_limits<std::int32_t>::max());
if (narrow) {
std::fill_n(minimum_, 33, std::numeric_limits<std::uint32_t>::max());
for (std::size_t i = 0; i < count_; ++i)
put((std::uint64_t(std::uint32_t(small_[i].key)) << 32) | std::uint32_t(small_[i].vertex));
mode_ = 1;
} else promote();
}
if (mode_ == 1 && std::uint64_t(key) - last_ > std::uint64_t(std::numeric_limits<std::int32_t>::max())) promote();
if (mode_ == 2) wide_.push({std::uint64_t(key), vertex});
else put((std::uint64_t(std::uint32_t(key)) << 32) | std::uint32_t(vertex));
++count_;
}
std::pair<T, int> pop() {
assert(count_);
if (mode_ == 0) {
std::size_t best = 0;
for (std::size_t i = 1; i < count_; ++i)
if (small_[i].key < small_[best].key) best = i;
State state = small_[best];
small_[best] = small_[--count_];
last_ = std::uint64_t(state.key);
return {state.key, state.vertex};
}
if (mode_ == 2) {
auto state = wide_.pop_value();
last_ = state.first;
--count_;
return {T(state.first), state.second};
}
if (buckets_[0].empty()) {
int index = std::countr_zero(occupied_) + 1;
last_ += std::uint32_t(minimum_[index] - std::uint32_t(last_));
minimum_[index] = std::numeric_limits<std::uint32_t>::max();
occupied_ &= occupied_ - 1;
if (buckets_[index].size() == 1) {
auto state = buckets_[index].back();
buckets_[index].clear();
--count_;
return {T(last_), int(std::uint32_t(state))};
}
for (auto state : buckets_[index]) put(state);
buckets_[index].clear();
}
auto state = buckets_[0].back();
buckets_[0].pop_back();
--count_;
return {T(last_), int(std::uint32_t(state))};
}
};
template<class T> class BinaryQueue {
using State = std::pair<T, int>;
std::vector<State> heap_;
public:
bool empty() const { return heap_.empty(); }
void push(T cost, int vertex) {
heap_.emplace_back(std::move(cost), vertex);
std::push_heap(heap_.begin(), heap_.end(), std::greater<State>());
}
State pop() {
std::pop_heap(heap_.begin(), heap_.end(), std::greater<State>());
State state = std::move(heap_.back());
heap_.pop_back();
return state;
}
};
template<class T>
using DistanceQueue = std::conditional_t<std::is_integral_v<T> && sizeof(T) <= 8, RadixQueue<T>, BinaryQueue<T>>;
}
#line 11 "components/dijkstra_topological.hpp"
namespace shortest_path_detail {
template<bool Path, class G, class T>
std::vector<T> topological_run(const G &g, int start, int target, T inf, std::vector<int> &parent) {
std::size_t n = std::size_t(g.size());
assert(n <= static_cast<std::size_t>(std::numeric_limits<int>::max()));
assert(start >= 0 && static_cast<std::size_t>(start) < n);
assert(inf > 0);
std::vector<T> distance(n, inf);
std::vector<std::size_t> indegree(n);
std::vector<int> ready;
ready.reserve(n);
for (std::size_t v = 0; v < n; ++v)
for (const auto &[to, weight] : g[int(v)]) {
assert(to >= 0 && static_cast<std::size_t>(to) < n);
assert(weight >= 0);
++indegree[to];
}
for (std::size_t v = 0; v < n; ++v)
if (!indegree[v]) ready.push_back(int(v));
distance[start] = 0;
auto improve = [&](int from, const T &cost, const T &allowance, int to, const auto &weight) {
if (reaches_limit(weight, allowance)) return false;
T next = cost + weight;
if (next >= distance[to]) return false;
if constexpr (Path) {
if (next >= distance[target]) return false;
parent[to] = from;
}
distance[to] = std::move(next);
return true;
};
for (std::size_t head = 0; head < ready.size(); ++head) {
int v = ready[head];
if constexpr (Path) if (v == target) return distance;
T cost = distance[v];
bool active = cost < inf;
if constexpr (Path) active &= cost < distance[target];
T allowance = active ? inf - cost : T(0);
for (const auto &[to, weight] : g[v]) {
if (active) improve(v, cost, allowance, to, weight);
if (--indegree[to] == 0) ready.push_back(to);
}
}
DistanceQueue<T> queue;
for (std::size_t v = 0; v < n; ++v) {
if (!indegree[v] || distance[v] == inf || g[v].empty()) continue;
if constexpr (Path) if (int(v) == target || distance[v] >= distance[target]) continue;
queue.push(distance[v], int(v));
}
while (!queue.empty()) {
const auto [cost, v] = queue.pop();
if (cost != distance[v]) continue;
if constexpr (Path) if (cost >= distance[target]) break;
T allowance = inf - cost;
for (const auto &[to, weight] : g[v]) {
if (!improve(v, cost, allowance, to, weight)) continue;
if constexpr (Path) if (to == target) continue;
if (!g[to].empty()) queue.push(distance[to], to);
}
}
return distance;
}
}