競技プログラミング用 C++ ライブラリ
graph/difference_constraints.hpp · GitHub で見る
共通ページ
整数変数に対する差分制約を扱います。解の存在判定・復元と、変数間の差や各変数の最大値・最小値を求められます。
#include "lib/graph/difference_constraints.hpp"
DifferenceConstraints<> system(3);
system.add_range(0, 1, 2, 5); // 2 <= x[1] - x[0] <= 5
system.add_lt(1, 2, 4); // x[2] - x[1] < 4
system.fix(0, 10); // x[0] = 10
auto result = system.solve();
if (result.feasible()) {
const auto &x = result.values(); // 全制約を満たす解の一つ
assert(x[0] == 10);
assert(result.max_difference(0, 2) == 8);
assert(result.min_difference(0, 1) == 2);
assert(result.upper_bound(2) == 18);
assert(!result.lower_bound(2)); // 下に非有界
auto upper = result.upper_bounds(0); // x[v] - x[0] の最大値: 0, 5, 8
}
DifferenceConstraints<Cost = std::int64_t>(n = 0) で変数の個数を指定します。変数番号は [0,n)、origin() は定数 0 を表す頂点 n です。二変数の制約・差の問い合わせでは origin() も指定できます。差の向きは全て x[v] - x[u] です。
既定の計算・戻り値は std::int64_t です。128 bit が必要な場合は DifferenceConstraints<__int128_t> を使ってください。Cost は 16 byte 以下の符号付き整数型で、戻り値の value_type は Cost が 8 byte 以下なら std::int64_t、それ以外なら __int128_t です。値と途中計算が型の範囲に収まるようにしてください。扱えない値を検出すると std::overflow_error を投げます。
| 制約追加 | 意味 |
|---|---|
add_le(u,v,c) |
x[v] - x[u] <= c |
add_ge(u,v,c) |
x[v] - x[u] >= c |
add_lt(u,v,c) |
x[v] - x[u] < c |
add_gt(u,v,c) |
x[v] - x[u] > c |
add_eq(u,v,c) |
x[v] - x[u] == c |
add_range(u,v,lower,upper) |
lower <= x[v] - x[u] <= upper |
add_upper_bound(v,c) |
x[v] <= c |
add_lower_bound(v,c) |
x[v] >= c |
fix(v,c) |
x[v] == c |
add_range(v,lower,upper) |
lower <= x[v] <= upper |
制約追加は ID を std::size_t で返し、等式・区間・固定値は 2 個の ID を std::pair で返します。constraint_count() はこの本数、constraints()[id] は x[to] - x[from] <= weight を表す {from,to,weight} です。reserve(count) にはこの本数の予約量を指定します。
solve() は Result を返します。結果は呼び出した時点の系を保持し、その後の制約追加に影響されません。
| 結果の操作 | 内容・返り値 |
|---|---|
feasible() |
全制約を同時に満たせるか |
size() / origin()
|
変数数/定数 0 の補助頂点 |
values() |
実現可能な解を const vector<value_type>& で取得。通常の変数のみ |
value(v) |
解の 1 変数。value(origin()) は 0 |
negative_cycle() |
矛盾を示す正規化済み制約の閉路。解があれば空 |
upper_bounds(source) |
全変数について x[v] - x[source] の最大値 |
upper_bounds() |
全変数について x[v] の最大値 |
max_difference(u,v) |
x[v] - x[u] の最大値 |
min_difference(u,v) |
x[v] - x[u] の最小値 |
upper_bound(v) / lower_bound(v)
|
x[v] の最大値/最小値 |
解がない場合は解・上下限を取得しないでください。negative_cycle() は元の制約辺を閉路の順に返し、その重みの総和は負になります。
values() は解の一つで、各変数を最大化した解ではありません。最大値・最小値は std::optional<value_type> で返し、std::nullopt はその方向に非有界であることを表します。有限な値は実際に取り得る極値です。upper_bounds は通常の変数に対応する vector<optional<value_type>> を返します。
同じ始点から複数の差を調べる場合は upper_bounds(source) を一度呼び、その結果を参照してください。max_difference などの個別の問い合わせは、呼び出すたびに計算を行います。
牛ゲーでは、制約を x[v] - x[u] <= c の形で表し、変数間の差の上限を最短路として求めます。この形にそろえた全ての制約で c >= 0 なら、Dijkstra 法をそのまま使えます。 add_le(u,v,c) のみで制約を追加する場合は、全ての c が非負であることが条件です。origin() に関する制約も含めます。
この条件を満たす場合、solve() は \(O(N+M)\) 時間で済み、その後の上下限問い合わせは Dijkstra 法と同じ計算量です。負の c を含む一般の場合でも、solve() が成功した後の上下限問い合わせは同じ計算量になります。
変数と origin() を合わせた頂点数を \(N\)、constraint_count() を \(M\) とします。64 bit の計算量では \(w=64\) とします。
| 操作・条件 | 64 bit | 128 bit |
|---|---|---|
| 制約追加 | 償却 \(O(1)\) | 償却 \(O(1)\) |
solve():一般の場合 |
最悪 \(O(N+NM)\) | 最悪 \(O(N+NM+M\log M)\) |
solve():上記の全ての c が非負の場合 |
\(O(N+M)\) | \(O(N+M)\) |
| 上下限・差の最大値・最小値の取得(1 回) | \(O(N+Mw)\) | \(O(N+M\log M)\) |
solve() と上下限の取得は \(O(N+M)\) 追加空間を使います。同じ変数同士の差の取得と、解・負閉路の参照は \(O(1)\) 時間です。
#ifndef DIFFERENCE_CONSTRAINTS_HPP
#define DIFFERENCE_CONSTRAINTS_HPP
#include "bellman_ford.hpp"
#include "dijkstra.hpp"
#include <optional>
template<class Cost = std::int64_t>
class DifferenceConstraints {
static_assert(std::numeric_limits<Cost>::is_integer && std::numeric_limits<Cost>::is_signed && sizeof(Cost) <= 16);
public:
using value_type = std::conditional_t<(sizeof(Cost) <= 8), std::int64_t, __int128_t>;
using Constraint = DirectedCSR<value_type>::Edge;
class Result {
friend class DifferenceConstraints;
int n_;
DirectedCSR<value_type> graph_;
std::vector<value_type> values_;
std::vector<Constraint> negative_cycle_;
explicit Result(int n) : n_(n) {}
void check([[maybe_unused]] int v) const { assert(0 <= v && v <= n_); }
value_type potential(int v) const { return v == n_ ? 0 : values_[v]; }
template<class Function>
auto with_distances(int source, Function &&function) const {
assert(feasible());
check(source);
if (!n_) return function(std::vector<value_type>{0});
auto distance = dijkstra(graph_, source, std::numeric_limits<value_type>::max());
if (std::find(distance.begin(), distance.end(), value_type(-1)) != distance.end())
for (int v = 0; v <= n_; ++v) if (distance[v] != -1)
for (auto [to, weight] : graph_[v])
if (distance[to] == -1) throw std::overflow_error("DifferenceConstraints distance");
return function(distance);
}
public:
Result(const Result &) = default;
Result &operator=(const Result &) = default;
Result(Result &&other) noexcept : n_(std::exchange(other.n_, 0)), graph_(std::move(other.graph_)),
values_(std::move(other.values_)), negative_cycle_(std::move(other.negative_cycle_)) {}
Result &operator=(Result &&other) noexcept {
if (this != &other) {
n_ = std::exchange(other.n_, 0);
graph_ = std::move(other.graph_);
values_ = std::move(other.values_);
negative_cycle_ = std::move(other.negative_cycle_);
}
return *this;
}
int size() const { return n_; }
int origin() const { return n_; }
bool feasible() const { return negative_cycle_.empty(); }
const std::vector<value_type> &values() const { assert(feasible()); return values_; }
value_type value(int v) const { assert(feasible()); check(v); return potential(v); }
const std::vector<Constraint> &negative_cycle() const { return negative_cycle_; }
std::vector<std::optional<value_type>> upper_bounds(int source) const {
return with_distances(source, [&](const auto &reduced) {
std::vector<std::optional<value_type>> result(n_);
for (int v = 0; v < n_; ++v)
if (reduced[v] != -1) result[v] = add_sub(reduced[v], potential(v), potential(source));
return result;
});
}
std::vector<std::optional<value_type>> upper_bounds() const { return upper_bounds(origin()); }
std::optional<value_type> max_difference(int u, int v) const {
assert(feasible());
check(u), check(v);
if (u == v) return 0;
return with_distances(u, [&](const auto &reduced) -> std::optional<value_type> {
if (reduced[v] == -1) return std::nullopt;
return add_sub(reduced[v], potential(v), potential(u));
});
}
std::optional<value_type> min_difference(int u, int v) const {
auto result = max_difference(v, u);
if (result) *result = checked_sub(0, *result);
return result;
}
std::optional<value_type> upper_bound(int v) const { return max_difference(origin(), v); }
std::optional<value_type> lower_bound(int v) const { return min_difference(origin(), v); }
};
private:
int n_;
std::vector<Constraint> constraints_;
void check([[maybe_unused]] int v) const { assert(0 <= v && v <= n_); }
std::size_t add(int u, int v, value_type bound) {
check(u), check(v);
constraints_.push_back({u, v, bound});
return constraints_.size() - 1;
}
static value_type checked_add(value_type a, value_type b) {
value_type result;
if (__builtin_add_overflow(a, b, &result)) throw std::overflow_error("DifferenceConstraints addition");
return result;
}
static value_type checked_sub(value_type a, value_type b) {
value_type result;
if (__builtin_sub_overflow(a, b, &result)) throw std::overflow_error("DifferenceConstraints subtraction");
return result;
}
static value_type add_sub(value_type a, value_type b, value_type c) {
if ((b < 0) == (c < 0)) return checked_add(a, checked_sub(b, c));
return checked_sub(checked_add(a, b), c);
}
public:
explicit DifferenceConstraints(int n = 0) : n_(n) { assert(0 <= n && n <= std::numeric_limits<int>::max() - 2); }
int size() const { return n_; }
int origin() const { return n_; }
std::size_t constraint_count() const { return constraints_.size(); }
const std::vector<Constraint> &constraints() const { return constraints_; }
void reserve(std::size_t count) { constraints_.reserve(count); }
std::size_t add_le(int u, int v, Cost bound) { return add(u, v, value_type(bound)); }
std::size_t add_ge(int u, int v, Cost bound) { return add(v, u, checked_sub(0, value_type(bound))); }
std::size_t add_lt(int u, int v, Cost bound) { return add(u, v, checked_sub(value_type(bound), 1)); }
std::size_t add_gt(int u, int v, Cost bound) { return add(v, u, checked_sub(-1, value_type(bound))); }
std::pair<std::size_t, std::size_t> add_eq(int u, int v, Cost value) {
value_type reverse = checked_sub(0, value_type(value));
return {add(u, v, value), add(v, u, reverse)};
}
std::pair<std::size_t, std::size_t> add_range(int u, int v, Cost lower, Cost upper) {
value_type reverse = checked_sub(0, value_type(lower));
return {add(v, u, reverse), add(u, v, upper)};
}
std::size_t add_upper_bound(int v, Cost bound) { return add_le(origin(), v, bound); }
std::size_t add_lower_bound(int v, Cost bound) { return add_ge(origin(), v, bound); }
std::pair<std::size_t, std::size_t> fix(int v, Cost value) { return add_eq(origin(), v, value); }
std::pair<std::size_t, std::size_t> add_range(int v, Cost lower, Cost upper) { return add_range(origin(), v, lower, upper); }
Result solve() const {
Result result(n_);
std::vector<Constraint> edges = constraints_;
edges.reserve(constraints_.size() + std::size_t(n_) + 1);
const int source = n_ + 1;
for (int v = 0; v <= n_; ++v) edges.push_back({source, v, 0});
{
DirectedCSR<value_type> graph(n_ + 2, edges);
auto found = bellman_ford<value_type>(graph, source);
if (found.has_negative_cycle()) {
for (std::size_t i = 0; i < found.negative_cycle_edges.size(); ++i) {
int from = found.negative_cycle[i];
auto [to, weight] = graph[from][found.negative_cycle_edges[i]];
assert(from <= n_ && to <= n_);
result.negative_cycle_.push_back({from, to, weight});
}
return result;
}
result.values_.resize(n_);
for (int v = 0; v < n_; ++v) result.values_[v] = checked_sub(found.distance[v], found.distance[n_]);
}
edges.resize(constraints_.size());
for (auto &edge : edges) {
edge.weight = add_sub(edge.weight, result.potential(edge.from), result.potential(edge.to));
assert(edge.weight >= 0);
if (edge.weight == std::numeric_limits<value_type>::max()) throw std::overflow_error("DifferenceConstraints reduced weight");
}
result.graph_ = DirectedCSR<value_type>(n_ + 1, edges);
return result;
}
};
#endif
#line 1 "graph/difference_constraints.hpp"
#line 1 "graph/bellman_ford.hpp"
#line 1 "components/shortest_path_scc.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <limits>
#include <vector>
namespace negative_path_detail {
struct Components {
std::vector<int> id, vertices;
std::vector<std::size_t> offset{0};
};
template<class Graph>
Components reachable_components(const Graph &g, int source) {
assert(std::size_t(g.size()) <= std::size_t(std::numeric_limits<int>::max()));
int n = static_cast<int>(g.size());
assert(0 <= source && source < n);
Components result;
result.id.assign(n, -1);
std::vector<int> index(n, -1), low(n), pending;
struct Frame { int vertex; std::size_t next; };
std::vector<Frame> stack;
int clock = 0, count = 0;
auto enter = [&](int v) {
index[v] = low[v] = clock++;
pending.push_back(v);
stack.push_back({v, 0});
};
enter(source);
while (!stack.empty()) {
int v = stack.back().vertex;
if (stack.back().next < g[v].size()) {
int to = g[v][stack.back().next++].first;
assert(0 <= to && to < n);
if (index[to] == -1) enter(to);
else if (result.id[to] == -1) low[v] = std::min(low[v], index[to]);
} else {
stack.pop_back();
if (low[v] == index[v]) {
int u;
do {
u = pending.back();
pending.pop_back();
result.id[u] = count;
result.vertices.push_back(u);
} while (u != v);
++count;
result.offset.push_back(result.vertices.size());
}
if (!stack.empty()) {
int parent = stack.back().vertex;
low[parent] = std::min(low[parent], low[v]);
}
}
}
return result;
}
}
#line 1 "components/directed_csr.hpp"
#line 7 "components/directed_csr.hpp"
#include <cstdint>
#include <memory>
#include <span>
#include <stdexcept>
#include <type_traits>
#include <utility>
#line 14 "components/directed_csr.hpp"
namespace directed_csr_detail { struct Access; }
template<class T>
class DirectedCSR {
public:
struct Edge { int from, to; T weight; };
using Arc = std::pair<int, T>;
using weight_type = T;
using distance_type = std::conditional_t<std::is_integral_v<T> && sizeof(T) < 8, std::int64_t, T>;
private:
friend struct directed_csr_detail::Access;
std::vector<std::size_t> offset_;
std::vector<Arc> arcs_;
int single_gap_ = -2;
bool unique_incoming_ = true;
void reset(int n, std::size_t m) {
assert(n >= 0);
offset_.assign(std::size_t(n) + 1, 0);
single_gap_ = -2;
unique_incoming_ = m <= std::size_t(n);
}
void count_edge(const Edge &edge, std::vector<std::uint64_t> &seen) {
assert(0 <= edge.from && edge.from < size() && 0 <= edge.to && edge.to < size());
++offset_[edge.from];
if (unique_incoming_) {
auto mask = std::uint64_t(1) << (edge.to % 64);
auto &word = seen[edge.to / 64];
unique_incoming_ = !(word & mask);
word |= mask;
}
}
void finish(std::span<const Edge> edges) {
const auto n = offset_.size() - 1;
single_gap_ = -2;
if (edges.size() >= n - (n != 0) && edges.size() <= n &&
std::all_of(offset_.begin(), offset_.end() - 1, [](std::size_t x) { return x <= 1; })) {
single_gap_ = -1;
if (edges.size() != n) single_gap_ = int(std::find(offset_.begin(), offset_.end() - 1, 0) - offset_.begin());
for (std::size_t v = 0; v <= n; ++v) offset_[v] = v - (single_gap_ >= 0 && v > std::size_t(single_gap_));
arcs_.resize(edges.size());
for (const auto &edge : edges) arcs_[edge.from - (single_gap_ >= 0 && edge.from > single_gap_)] = {edge.to, edge.weight};
return;
}
std::size_t active = offset_[0] != 0;
for (std::size_t v = 1; v < offset_.size(); ++v) {
active += offset_[v] != 0;
offset_[v] += offset_[v - 1];
}
arcs_.resize(edges.size());
std::size_t i = edges.size();
#if defined(__GNUC__) || defined(__clang__)
if (active >= 8192) {
for (; i > 32; --i) {
const auto from = edges[i - 33].from;
__builtin_prefetch(&offset_[from], 1, 3);
__builtin_prefetch(&arcs_[offset_[from] - 1], 1, 3);
const auto &edge = edges[i - 1];
arcs_[--offset_[edge.from]] = {edge.to, edge.weight};
}
}
#endif
for (; i; --i) {
const auto &edge = edges[i - 1];
arcs_[--offset_[edge.from]] = {edge.to, edge.weight};
}
}
void clear_edges() {
single_gap_ = -2;
unique_incoming_ = true;
std::fill(offset_.begin(), offset_.end(), 0);
arcs_.clear();
}
public:
explicit DirectedCSR(int n = 0) {
assert(n >= 0);
offset_.assign(std::size_t(n) + 1, 0);
}
DirectedCSR(int n, std::span<const Edge> edges) { build(n, edges); }
template<class Producer>
DirectedCSR(int n, std::size_t m, Producer &&produce) { build(n, m, std::forward<Producer>(produce)); }
void build(int n, std::span<const Edge> edges) {
reset(n, edges.size());
try {
std::vector<std::uint64_t> seen(unique_incoming_ ? (std::size_t(n) + 63) / 64 : 0);
for (const auto &edge : edges) count_edge(edge, seen);
finish(edges);
}
catch (...) { clear_edges(); throw; }
}
template<class Producer>
void build(int n, std::size_t m, Producer &&produce) {
reset(n, m);
try {
std::vector<std::uint64_t> seen(unique_incoming_ ? (std::size_t(n) + 63) / 64 : 0);
auto edges = std::make_unique_for_overwrite<Edge[]>(m);
std::size_t count = 0;
auto emit = [&](Edge edge) {
if (count == m) throw std::length_error("DirectedCSR edge count");
count_edge(edge, seen);
edges[count++] = std::move(edge);
};
std::forward<Producer>(produce)(emit);
if (count != m) throw std::length_error("DirectedCSR edge count");
finish(std::span<const Edge>(edges.get(), m));
} catch (...) { clear_edges(); throw; }
}
int size() const { return offset_.empty() ? 0 : int(offset_.size() - 1); }
bool empty() const { return size() == 0; }
std::size_t edge_count() const { return arcs_.size(); }
std::span<const Arc> operator[](int v) const {
assert(0 <= v && v < size());
return std::span<const Arc>(arcs_).subspan(offset_[v], offset_[v + 1] - offset_[v]);
}
};
namespace directed_csr_detail {
template<class T>
struct SingleEdgeView {
std::span<const typename DirectedCSR<T>::Arc> arcs;
int n, gap;
int size() const { return n; }
std::span<const typename DirectedCSR<T>::Arc> operator[](int v) const {
if (v == gap) return {};
return arcs.subspan(v - (gap >= 0 && v > gap), 1);
}
};
struct Access {
template<class T>
static bool unique_incoming(const DirectedCSR<T> &g) { return g.offset_.empty() || g.unique_incoming_; }
template<class T>
static bool has_single_edge_layout(const DirectedCSR<T> &g) { return !g.offset_.empty() && g.single_gap_ >= -1; }
template<class T>
static SingleEdgeView<T> single_edge_view(const DirectedCSR<T> &g) { return {g.arcs_, g.size(), g.single_gap_}; }
};
}
#line 1 "components/RadixHeap.hpp"
#line 5 "components/RadixHeap.hpp"
#include <bit>
#line 13 "components/RadixHeap.hpp"
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 8 "graph/bellman_ford.hpp"
#include <functional>
#line 12 "graph/bellman_ford.hpp"
template<class Distance>
struct BellmanFordResult {
std::vector<Distance> distance;
std::vector<int> parent, negative_cycle;
std::vector<std::size_t> parent_edge, negative_cycle_edges;
Distance infinity;
int source;
bool has_negative_cycle() const { return !negative_cycle.empty(); }
bool reachable(int v) const {
assert(!has_negative_cycle() && 0 <= v && std::size_t(v) < distance.size());
return distance[v] != infinity;
}
std::vector<int> path(int v) const {
if (!reachable(v)) return {};
std::vector<int> result;
for (; v != source; v = parent[v]) result.push_back(v);
result.push_back(source);
std::reverse(result.begin(), result.end());
return result;
}
std::vector<std::size_t> path_edges(int v) const {
if (!reachable(v)) return {};
std::vector<std::size_t> result;
for (; v != source; v = parent[v]) result.push_back(parent_edge[v]);
std::reverse(result.begin(), result.end());
return result;
}
};
namespace negative_path_detail {
template<class Distance, class Weight>
Distance add(Distance a, Weight b) {
static_assert(std::numeric_limits<Distance>::is_integer && std::numeric_limits<Distance>::is_signed);
static_assert(std::numeric_limits<Weight>::is_integer && std::numeric_limits<Weight>::is_signed);
static_assert(std::numeric_limits<Distance>::digits >= std::numeric_limits<Weight>::digits);
Distance value;
#if defined(__GNUC__) || defined(__clang__)
if (__builtin_add_overflow(a, Distance(b), &value)) throw std::overflow_error("Bellman-Ford distance");
#else
Distance w = b;
if ((w > 0 && a > std::numeric_limits<Distance>::max() - w) ||
(w < 0 && a < std::numeric_limits<Distance>::lowest() - w)) throw std::overflow_error("Bellman-Ford distance");
value = a + w;
#endif
if (value == std::numeric_limits<Distance>::max()) throw std::overflow_error("Bellman-Ford infinity");
return value;
}
template<bool Decompose, int Passes, class Distance, class Graph>
BellmanFordResult<Distance> solve(const Graph &g, int source) {
assert(std::size_t(g.size()) <= std::size_t(std::numeric_limits<int>::max()));
int n = static_cast<int>(g.size());
assert(0 <= source && source < n);
Distance inf = std::numeric_limits<Distance>::max();
BellmanFordResult<Distance> result{std::vector<Distance>(n, inf), std::vector<int>(n, -1), {},
std::vector<std::size_t>(n, std::size_t(-1)), {}, inf, source};
result.distance[source] = 0;
result.parent[source] = source;
auto &d = result.distance;
std::vector<int> active, order;
auto relax = [&](int v, std::size_t i) {
const auto &[to, w] = g[v][i];
Distance next = add(d[v], w);
if (next >= d[to]) return false;
d[to] = next;
result.parent[to] = v;
result.parent_edge[to] = i;
return true;
};
for (int pass = 0; pass < Passes; ++pass) {
bool changed = false;
for (int v = 0; v < n; ++v) if (d[v] != inf)
for (std::size_t i = 0; i < g[v].size(); ++i) changed |= relax(v, i);
if (!changed) return result;
}
std::vector<int> position(n, -1);
std::vector<unsigned char> labeled(n);
Components components;
if constexpr (Decompose) components = reachable_components(g, source);
else {
components.id.assign(n, 0);
components.vertices.resize(n);
for (int v = 0; v < n; ++v) components.vertices[v] = v;
components.offset.push_back(n);
}
struct Frame { int vertex; std::size_t next, incoming; };
std::vector<Frame> stack;
using State = std::pair<Distance, int>;
constexpr bool radix = std::is_integral_v<Distance> && sizeof(Distance) <= 8;
std::conditional_t<radix, RadixHeap<Distance>, std::vector<State>> heap;
for (int c = static_cast<int>(components.offset.size()) - 2; c >= 0; --c) {
auto begin = components.offset[c], end = components.offset[c + 1];
auto internal = [&](int to) { return components.id[to] == c; };
bool negative = !Decompose;
Distance minimum = inf;
for (auto j = begin; j < end; ++j) {
int v = components.vertices[j];
minimum = std::min(minimum, d[v]);
if constexpr (Decompose)
for (const auto &[to, w] : g[v]) if (internal(to) && w < 0) negative = true;
}
if (minimum == inf) continue;
if (negative) {
active.clear();
for (auto j = begin; j < end; ++j) {
int v = components.vertices[j];
if (d[v] != inf) active.push_back(v);
}
while (!active.empty()) {
order.clear();
for (int v : active) labeled[v] = 0;
for (int root : active) {
if (position[root] != -1) continue;
bool useful = false;
for (const auto &[to, w] : g[root])
if (internal(to) && add(d[root], w) < d[to]) { useful = true; break; }
if (!useful) continue;
position[root] = 0;
stack.push_back({root, 0, std::size_t(-1)});
while (!stack.empty()) {
int v = stack.back().vertex;
if (stack.back().next == g[v].size()) {
position[v] = -2;
order.push_back(v);
stack.pop_back();
continue;
}
std::size_t i = stack.back().next++;
int to = g[v][i].first;
if (!internal(to) || !relax(v, i)) continue;
if (position[to] >= 0) {
for (auto j = std::size_t(position[to]); j < stack.size(); ++j) {
result.negative_cycle.push_back(stack[j].vertex);
if (j + 1 < stack.size()) result.negative_cycle_edges.push_back(stack[j + 1].incoming);
}
result.negative_cycle.push_back(to);
result.negative_cycle_edges.push_back(i);
return result;
}
if (position[to] == -1) {
position[to] = static_cast<int>(stack.size());
stack.push_back({to, 0, i});
}
}
}
active.clear();
for (auto it = order.rbegin(); it != order.rend(); ++it) {
int v = *it;
for (std::size_t i = 0; i < g[v].size(); ++i) {
int to = g[v][i].first;
if (internal(to) && relax(v, i) && !labeled[to]) active.push_back(to), labeled[to] = 1;
}
}
for (int v : order) position[v] = -1;
}
} else if (end - begin > 1) {
auto push = [&](Distance cost, int v) {
if constexpr (radix) heap.push({cost, v});
else { heap.emplace_back(cost, v); std::push_heap(heap.begin(), heap.end(), std::greater<State>()); }
};
if constexpr (radix) heap.clear(minimum);
for (auto j = begin; j < end; ++j) {
int v = components.vertices[j];
if (d[v] != inf) push(d[v], v);
}
while (!heap.empty()) {
auto [cost, v] = [&] {
if constexpr (radix) return heap.pop_value();
else { std::pop_heap(heap.begin(), heap.end(), std::greater<State>()); auto state = heap.back(); heap.pop_back(); return state; }
}();
if (cost != d[v]) continue;
for (std::size_t i = 0; i < g[v].size(); ++i) {
int to = g[v][i].first;
if (internal(to) && relax(v, i)) push(d[to], to);
}
}
}
if constexpr (Decompose)
for (auto j = begin; j < end; ++j) {
int v = components.vertices[j];
for (std::size_t i = 0; i < g[v].size(); ++i) if (!internal(g[v][i].first)) relax(v, i);
}
}
return result;
}
}
template<class Distance = std::int64_t, class Graph>
BellmanFordResult<Distance> bellman_ford(const Graph &g, int source) {
return negative_path_detail::solve<true, 2, Distance>(g, source);
}
template<class Distance = std::int64_t, class Graph>
BellmanFordResult<Distance> goldberg_radzik(const Graph &g, int source) {
return negative_path_detail::solve<false, 0, Distance>(g, source);
}
#line 1 "graph/dijkstra.hpp"
#line 1 "components/dijkstra_queue.hpp"
#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 1 "components/dijkstra_topological.hpp"
#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;
}
}
#line 1 "components/dijkstra_unique.hpp"
#line 9 "components/dijkstra_unique.hpp"
namespace shortest_path_detail {
template<class G, class T>
std::pair<T, std::vector<int>> unique_path(const G &g, int st, int target, T inf, std::vector<int> &parent) {
using State = std::pair<T, int>;
std::vector<State> pending;
pending.emplace_back(T(0), st);
while (!pending.empty()) {
auto [cost, v] = std::move(pending.back());
pending.pop_back();
for (const auto &first : g[v]) {
const auto *edge = &first;
int from = v;
T prefix = cost;
for (;;) {
const auto &[to, weight] = *edge;
assert(weight >= 0);
if (to == st) break;
if (reaches_limit(weight, T(inf - prefix))) break;
T next = prefix + weight;
if (to == target) {
std::vector<int> path{to};
for (int u = from; u != st; u = parent[u]) path.push_back(u);
path.push_back(st);
std::reverse(path.begin(), path.end());
return {std::move(next), std::move(path)};
}
const auto &outgoing = g[to];
if (outgoing.empty()) break;
parent[to] = from;
if (outgoing.size() != 1) {
pending.emplace_back(std::move(next), to);
break;
}
from = to;
edge = &outgoing[0];
prefix = std::move(next);
}
}
}
return {T(-1), {}};
}
}
#line 16 "graph/dijkstra.hpp"
inline constexpr std::int64_t DIJKSTRA_INF = 4'000'000'000'000'000'000;
namespace shortest_path_detail {
template<class T> T infinity() {
if constexpr (std::numeric_limits<T>::is_bounded && std::numeric_limits<T>::is_integer && std::numeric_limits<T>::digits < 62)
return std::numeric_limits<T>::max();
else return T(DIJKSTRA_INF);
}
template<bool Path, class G, class T>
std::vector<T> run(const G &g, int st, int target, T inf, std::vector<int> &parent) {
const auto n = static_cast<std::size_t>(g.size());
assert(n <= static_cast<std::size_t>(std::numeric_limits<int>::max()));
assert(st >= 0 && static_cast<std::size_t>(st) < n);
assert(inf > 0);
std::vector<T> d(n, inf);
d[st] = 0;
DistanceQueue<T> pq;
pq.push(0, st);
while (!pq.empty()) {
const auto [cost, v] = pq.pop();
if (d[v] != cost) continue;
if constexpr (Path) if (cost >= d[target]) break;
T allowance = inf - cost;
for (const auto &[to, c] : g[v]) {
assert(to >= 0 && static_cast<std::size_t>(to) < n);
assert(c >= 0);
if (reaches_limit(c, allowance)) continue;
T next = cost + c;
if (next >= d[to]) continue;
if constexpr (Path) {
if (next >= d[target]) continue;
parent[to] = v;
}
d[to] = next;
if constexpr (Path) if (to == target) continue;
if (!g[to].empty()) pq.push(std::move(next), to);
}
}
return d;
}
template<bool Topological, class G, class T>
std::vector<T> distances(const G &g, int st, T inf) {
std::vector<int> parent;
auto d = [&] {
if constexpr (Topological) return topological_run<false>(g, st, -1, inf, parent);
else return run<false>(g, st, -1, inf, parent);
}();
for (T &val : d)
if (val == inf) val = -1;
return d;
}
template<bool Topological, class G, class T>
std::pair<T, std::vector<int>> path(const G &g, int st, int target, T inf) {
[[maybe_unused]] const auto n = static_cast<std::size_t>(g.size());
assert(n <= static_cast<std::size_t>(std::numeric_limits<int>::max()));
assert(st >= 0 && static_cast<std::size_t>(st) < n);
assert(target >= 0 && static_cast<std::size_t>(target) < n);
assert(inf > 0);
if (st == target) return {T(0), {st}};
if (g[st].empty()) return {T(-1), {}};
if (g[st].size() == 1) {
using Weight = std::remove_cvref_t<decltype(g[st][0].second)>;
std::vector<int> direct{st};
T cost = 0;
int v = st, checkpoint = st;
std::size_t power = 1, length = 0;
while (g[v].size() == 1) {
const auto &[to, weight] = g[v][0];
assert(to >= 0 && static_cast<std::size_t>(to) < n);
assert(weight >= 0);
if (reaches_limit(weight, T(inf - cost))) return {T(-1), {}};
cost += weight;
v = to;
direct.push_back(v);
if (v == target) return {std::move(cost), std::move(direct)};
if (v == checkpoint) return {T(-1), {}};
if (++length == power) {
checkpoint = v;
power *= 2;
length = 0;
}
}
if (g[v].empty()) return {T(-1), {}};
if constexpr (std::numeric_limits<Weight>::is_integer && std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_bounded) {
auto suffix = shortest_path_detail::path<Topological>(g, v, target, T(inf - cost));
if (suffix.first == T(-1)) return {T(-1), {}};
direct.pop_back();
direct.insert(direct.end(), suffix.second.begin(), suffix.second.end());
return {cost + suffix.first, std::move(direct)};
}
}
std::vector<int> parent(g.size(), -1);
if constexpr (requires { directed_csr_detail::Access::unique_incoming(g); })
if (directed_csr_detail::Access::unique_incoming(g)) return unique_path(g, st, target, inf, parent);
auto d = [&] {
if constexpr (Topological) return topological_run<true>(g, st, target, inf, parent);
else return run<true>(g, st, target, inf, parent);
}();
if (d[target] == inf) return {T(-1), {}};
std::vector<int> path;
for (int v = target; v != st; v = parent[v]) path.push_back(v);
path.push_back(st);
std::reverse(path.begin(), path.end());
return {std::move(d[target]), std::move(path)};
}
}
template<bool Topological, class T>
std::vector<T> dijkstra(const std::vector<std::vector<std::pair<int, T>>> &g, int st, T inf = shortest_path_detail::infinity<T>()) {
return shortest_path_detail::distances<Topological>(g, st, inf);
}
template<class T>
std::vector<T> dijkstra(const std::vector<std::vector<std::pair<int, T>>> &g, int st, T inf = shortest_path_detail::infinity<T>()) {
return dijkstra<false>(g, st, inf);
}
template<bool Topological, class T>
std::pair<T, std::vector<int>> dijkstra_path(const std::vector<std::vector<std::pair<int, T>>> &g, int st, int target, T inf = shortest_path_detail::infinity<T>()) {
return shortest_path_detail::path<Topological>(g, st, target, inf);
}
template<class T>
std::pair<T, std::vector<int>> dijkstra_path(const std::vector<std::vector<std::pair<int, T>>> &g, int st, int target, T inf = shortest_path_detail::infinity<T>()) {
return dijkstra_path<false>(g, st, target, inf);
}
template<bool Topological, class W, class T = typename DirectedCSR<W>::distance_type>
std::vector<T> dijkstra(const DirectedCSR<W> &g, int st, T inf = shortest_path_detail::infinity<T>()) {
return shortest_path_detail::distances<Topological>(g, st, inf);
}
template<class W, class T = typename DirectedCSR<W>::distance_type>
std::vector<T> dijkstra(const DirectedCSR<W> &g, int st, T inf = shortest_path_detail::infinity<T>()) {
return dijkstra<false>(g, st, inf);
}
template<bool Topological, class W, class T = typename DirectedCSR<W>::distance_type>
std::pair<T, std::vector<int>> dijkstra_path(const DirectedCSR<W> &g, int st, int target, T inf = shortest_path_detail::infinity<T>()) {
if (directed_csr_detail::Access::has_single_edge_layout(g))
return shortest_path_detail::path<Topological>(directed_csr_detail::Access::single_edge_view(g), st, target, inf);
return shortest_path_detail::path<Topological>(g, st, target, inf);
}
template<class W, class T = typename DirectedCSR<W>::distance_type>
std::pair<T, std::vector<int>> dijkstra_path(const DirectedCSR<W> &g, int st, int target, T inf = shortest_path_detail::infinity<T>()) {
return dijkstra_path<false>(g, st, target, inf);
}
#line 6 "graph/difference_constraints.hpp"
#include <optional>
template<class Cost = std::int64_t>
class DifferenceConstraints {
static_assert(std::numeric_limits<Cost>::is_integer && std::numeric_limits<Cost>::is_signed && sizeof(Cost) <= 16);
public:
using value_type = std::conditional_t<(sizeof(Cost) <= 8), std::int64_t, __int128_t>;
using Constraint = DirectedCSR<value_type>::Edge;
class Result {
friend class DifferenceConstraints;
int n_;
DirectedCSR<value_type> graph_;
std::vector<value_type> values_;
std::vector<Constraint> negative_cycle_;
explicit Result(int n) : n_(n) {}
void check([[maybe_unused]] int v) const { assert(0 <= v && v <= n_); }
value_type potential(int v) const { return v == n_ ? 0 : values_[v]; }
template<class Function>
auto with_distances(int source, Function &&function) const {
assert(feasible());
check(source);
if (!n_) return function(std::vector<value_type>{0});
auto distance = dijkstra(graph_, source, std::numeric_limits<value_type>::max());
if (std::find(distance.begin(), distance.end(), value_type(-1)) != distance.end())
for (int v = 0; v <= n_; ++v) if (distance[v] != -1)
for (auto [to, weight] : graph_[v])
if (distance[to] == -1) throw std::overflow_error("DifferenceConstraints distance");
return function(distance);
}
public:
Result(const Result &) = default;
Result &operator=(const Result &) = default;
Result(Result &&other) noexcept : n_(std::exchange(other.n_, 0)), graph_(std::move(other.graph_)),
values_(std::move(other.values_)), negative_cycle_(std::move(other.negative_cycle_)) {}
Result &operator=(Result &&other) noexcept {
if (this != &other) {
n_ = std::exchange(other.n_, 0);
graph_ = std::move(other.graph_);
values_ = std::move(other.values_);
negative_cycle_ = std::move(other.negative_cycle_);
}
return *this;
}
int size() const { return n_; }
int origin() const { return n_; }
bool feasible() const { return negative_cycle_.empty(); }
const std::vector<value_type> &values() const { assert(feasible()); return values_; }
value_type value(int v) const { assert(feasible()); check(v); return potential(v); }
const std::vector<Constraint> &negative_cycle() const { return negative_cycle_; }
std::vector<std::optional<value_type>> upper_bounds(int source) const {
return with_distances(source, [&](const auto &reduced) {
std::vector<std::optional<value_type>> result(n_);
for (int v = 0; v < n_; ++v)
if (reduced[v] != -1) result[v] = add_sub(reduced[v], potential(v), potential(source));
return result;
});
}
std::vector<std::optional<value_type>> upper_bounds() const { return upper_bounds(origin()); }
std::optional<value_type> max_difference(int u, int v) const {
assert(feasible());
check(u), check(v);
if (u == v) return 0;
return with_distances(u, [&](const auto &reduced) -> std::optional<value_type> {
if (reduced[v] == -1) return std::nullopt;
return add_sub(reduced[v], potential(v), potential(u));
});
}
std::optional<value_type> min_difference(int u, int v) const {
auto result = max_difference(v, u);
if (result) *result = checked_sub(0, *result);
return result;
}
std::optional<value_type> upper_bound(int v) const { return max_difference(origin(), v); }
std::optional<value_type> lower_bound(int v) const { return min_difference(origin(), v); }
};
private:
int n_;
std::vector<Constraint> constraints_;
void check([[maybe_unused]] int v) const { assert(0 <= v && v <= n_); }
std::size_t add(int u, int v, value_type bound) {
check(u), check(v);
constraints_.push_back({u, v, bound});
return constraints_.size() - 1;
}
static value_type checked_add(value_type a, value_type b) {
value_type result;
if (__builtin_add_overflow(a, b, &result)) throw std::overflow_error("DifferenceConstraints addition");
return result;
}
static value_type checked_sub(value_type a, value_type b) {
value_type result;
if (__builtin_sub_overflow(a, b, &result)) throw std::overflow_error("DifferenceConstraints subtraction");
return result;
}
static value_type add_sub(value_type a, value_type b, value_type c) {
if ((b < 0) == (c < 0)) return checked_add(a, checked_sub(b, c));
return checked_sub(checked_add(a, b), c);
}
public:
explicit DifferenceConstraints(int n = 0) : n_(n) { assert(0 <= n && n <= std::numeric_limits<int>::max() - 2); }
int size() const { return n_; }
int origin() const { return n_; }
std::size_t constraint_count() const { return constraints_.size(); }
const std::vector<Constraint> &constraints() const { return constraints_; }
void reserve(std::size_t count) { constraints_.reserve(count); }
std::size_t add_le(int u, int v, Cost bound) { return add(u, v, value_type(bound)); }
std::size_t add_ge(int u, int v, Cost bound) { return add(v, u, checked_sub(0, value_type(bound))); }
std::size_t add_lt(int u, int v, Cost bound) { return add(u, v, checked_sub(value_type(bound), 1)); }
std::size_t add_gt(int u, int v, Cost bound) { return add(v, u, checked_sub(-1, value_type(bound))); }
std::pair<std::size_t, std::size_t> add_eq(int u, int v, Cost value) {
value_type reverse = checked_sub(0, value_type(value));
return {add(u, v, value), add(v, u, reverse)};
}
std::pair<std::size_t, std::size_t> add_range(int u, int v, Cost lower, Cost upper) {
value_type reverse = checked_sub(0, value_type(lower));
return {add(v, u, reverse), add(u, v, upper)};
}
std::size_t add_upper_bound(int v, Cost bound) { return add_le(origin(), v, bound); }
std::size_t add_lower_bound(int v, Cost bound) { return add_ge(origin(), v, bound); }
std::pair<std::size_t, std::size_t> fix(int v, Cost value) { return add_eq(origin(), v, value); }
std::pair<std::size_t, std::size_t> add_range(int v, Cost lower, Cost upper) { return add_range(origin(), v, lower, upper); }
Result solve() const {
Result result(n_);
std::vector<Constraint> edges = constraints_;
edges.reserve(constraints_.size() + std::size_t(n_) + 1);
const int source = n_ + 1;
for (int v = 0; v <= n_; ++v) edges.push_back({source, v, 0});
{
DirectedCSR<value_type> graph(n_ + 2, edges);
auto found = bellman_ford<value_type>(graph, source);
if (found.has_negative_cycle()) {
for (std::size_t i = 0; i < found.negative_cycle_edges.size(); ++i) {
int from = found.negative_cycle[i];
auto [to, weight] = graph[from][found.negative_cycle_edges[i]];
assert(from <= n_ && to <= n_);
result.negative_cycle_.push_back({from, to, weight});
}
return result;
}
result.values_.resize(n_);
for (int v = 0; v < n_; ++v) result.values_[v] = checked_sub(found.distance[v], found.distance[n_]);
}
edges.resize(constraints_.size());
for (auto &edge : edges) {
edge.weight = add_sub(edge.weight, result.potential(edge.from), result.potential(edge.to));
assert(edge.weight >= 0);
if (edge.weight == std::numeric_limits<value_type>::max()) throw std::overflow_error("DifferenceConstraints reduced weight");
}
result.graph_ = DirectedCSR<value_type>(n_ + 1, edges);
return result;
}
};