Bellman-Ford
(graph/bellman_ford.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/bellman_ford.hpp"
Overview
Bellman-Ford shortest paths for graphs that may contain negative edge costs. It also marks vertices reachable from a negative cycle that is reachable from the source set.
The algorithm relaxes every edge up to N times. If a distance can still be
improved on the N-th relaxation, that improvement must come from a negative
cycle. Every vertex reachable from such a cycle is marked as negative.
Use Bellman-Ford when negative edge costs are possible. If all edge costs are non-negative, Dijkstra is much faster.
Graph Orientation
Direction is respected. bellman_ford works on directed graphs as written, and
also on undirected graphs built with add_edge.
How to Use It
Call bellman_ford(g, s) for one source, or bellman_ford(g, sources) for
multiple starting vertices.
The result contains these members:
| Member | Type / Signature | Meaning |
|---|---|---|
dist |
std::vector<T> |
dist[v] is the best finite distance found from the source set, or inf if unreachable. |
parent |
std::vector<int> |
parent[v] is the previous vertex on the stored path, or -1. |
parent_edge |
std::vector<int> |
parent_edge[v] is the edge id used to enter v, or -1. |
negative |
std::vector<bool> |
negative[v] is whether v is reachable from a reachable negative cycle. |
inf |
T |
The unreachable-distance sentinel used by this run. |
has_negative_cycle |
bool |
Whether any reachable vertex is affected by a negative cycle. |
reachable |
bool reachable(int v) const |
Returns whether v was reached at all. |
affected_by_negative_cycle |
bool affected_by_negative_cycle(int v) const |
Returns negative[v]. |
path |
std::vector<int> path(int t) const |
Restores a path to t. Requires that t is reachable and not negative. |
If negative[v] is true, the shortest distance to v is not well-defined
because it can be made arbitrarily small.
Functions
| Function | Signature | Description | Complexity |
|---|---|---|---|
bellman_ford |
template <class T> BellmanFordResult<T> bellman_ford(const Graph<T>& g, int s, T inf = std::numeric_limits<T>::max() / T(4)) |
Runs from one source. | $O(N \cdot M)$ |
bellman_ford |
template <class T> BellmanFordResult<T> bellman_ford(const Graph<T>& g, const std::vector<int>& sources, T inf = std::numeric_limits<T>::max() / T(4)) |
Runs from multiple sources. | $O(N \cdot M)$ |
Example
#include "graph/bellman_ford.hpp"
#include "graph/graph.hpp"
#include <iostream>
int main() {
m1une::graph::Graph<long long> g(4);
g.add_directed_edge(0, 1, 1);
g.add_directed_edge(1, 2, -3);
g.add_directed_edge(2, 1, 1);
g.add_directed_edge(2, 3, 1);
auto res = m1une::graph::bellman_ford(g, 0);
std::cout << res.has_negative_cycle << "\n"; // 1
std::cout << res.affected_by_negative_cycle(3) << "\n"; // 1
}
Depends on
Required by
Graph All
(graph/all.hpp)
Directed Graph Algorithms
(graph/directed.hpp)
Shortest Path
(graph/shortest_path.hpp)
Undirected Graph Algorithms
(graph/undirected.hpp)
Verified with
verify/graph/cow_game.test.cpp
verify/graph/graph_algorithms.test.cpp
verify/graph/range_edge_graph.test.cpp
Code
#ifndef M1UNE_GRAPH_BELLMAN_FORD_HPP
#define M1UNE_GRAPH_BELLMAN_FORD_HPP 1
#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <vector>
#include "graph.hpp"
namespace m1une {
namespace graph {
template <class T>
struct BellmanFordResult {
std::vector<T> dist;
std::vector<int> parent;
std::vector<int> parent_edge;
std::vector<bool> negative;
T inf;
bool has_negative_cycle;
bool reachable(int v) const {
assert(0 <= v && v < int(dist.size()));
return dist[v] != inf;
}
bool affected_by_negative_cycle(int v) const {
assert(0 <= v && v < int(negative.size()));
return negative[v];
}
std::vector<int> path(int t) const {
assert(reachable(t));
assert(!affected_by_negative_cycle(t));
std::vector<int> result;
for (int v = t; v != -1; v = parent[v]) result.push_back(v);
std::reverse(result.begin(), result.end());
return result;
}
};
template <class T>
BellmanFordResult<T> bellman_ford(const Graph<T>& g, const std::vector<int>& sources,
T inf = std::numeric_limits<T>::max() / T(4)) {
int n = g.size();
BellmanFordResult<T> result;
result.dist.assign(n, inf);
result.parent.assign(n, -1);
result.parent_edge.assign(n, -1);
result.negative.assign(n, false);
result.inf = inf;
result.has_negative_cycle = false;
for (int s : sources) {
assert(0 <= s && s < n);
result.dist[s] = T(0);
}
std::vector<int> relaxed_vertices;
for (int iter = 0; iter < n; iter++) {
bool updated = false;
for (int v = 0; v < n; v++) {
if (result.dist[v] == inf) continue;
for (const auto& e : g[v]) {
if (!e.alive) continue;
T nd = result.dist[v] + e.cost;
if (result.dist[e.to] <= nd) continue;
result.dist[e.to] = nd;
result.parent[e.to] = v;
result.parent_edge[e.to] = e.id;
updated = true;
if (iter == n - 1) relaxed_vertices.push_back(e.to);
}
}
if (!updated) break;
}
std::queue<int> que;
for (int v : relaxed_vertices) {
if (result.negative[v]) continue;
result.negative[v] = true;
que.push(v);
}
while (!que.empty()) {
int v = que.front();
que.pop();
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (result.negative[e.to]) continue;
result.negative[e.to] = true;
que.push(e.to);
}
}
for (bool x : result.negative) result.has_negative_cycle = result.has_negative_cycle || x;
return result;
}
template <class T>
BellmanFordResult<T> bellman_ford(const Graph<T>& g, int s, T inf = std::numeric_limits<T>::max() / T(4)) {
return bellman_ford(g, std::vector<int>{s}, inf);
}
} // namespace graph
} // namespace m1une
#endif // M1UNE_GRAPH_BELLMAN_FORD_HPP#line 1 "graph/bellman_ford.hpp"
#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <vector>
#line 1 "graph/graph.hpp"
#include <array>
#line 6 "graph/graph.hpp"
#include <utility>
#line 8 "graph/graph.hpp"
namespace m1une {
namespace graph {
template <class T = int>
struct Edge {
using cost_type = T;
int from;
int to;
T cost;
int id;
bool alive;
Edge() : from(-1), to(-1), cost(T()), id(-1), alive(true) {}
Edge(int from_, int to_, T cost_ = T(1), int id_ = -1, bool alive_ = true)
: from(from_), to(to_), cost(cost_), id(id_), alive(alive_) {}
int other(int v) const {
assert(v == from || v == to);
return from ^ to ^ v;
}
};
template <class T = int>
struct Graph {
using edge_type = Edge<T>;
using cost_type = T;
private:
struct EdgePositions {
std::array<std::pair<int, int>, 2> value{};
int size = 0;
void push_back(std::pair<int, int> position) {
assert(size < 2);
value[size++] = position;
}
};
int _n;
int _edge_count;
std::vector<std::vector<edge_type>> _g;
std::vector<EdgePositions> _edge_positions;
public:
Graph() : _n(0), _edge_count(0) {}
explicit Graph(int n) : _n(n), _edge_count(0), _g(n) {
assert(0 <= n);
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int edge_count() const {
return _edge_count;
}
int add_vertex() {
_g.emplace_back();
return _n++;
}
int add_directed_edge(int from, int to, T cost = T(1)) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int id = _edge_count++;
int idx = int(_g[from].size());
_g[from].push_back(edge_type(from, to, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({from, idx});
return id;
}
int add_edge(int u, int v, T cost = T(1)) {
assert(0 <= u && u < _n);
assert(0 <= v && v < _n);
int id = _edge_count++;
int u_idx = int(_g[u].size());
_g[u].push_back(edge_type(u, v, cost, id));
int v_idx = int(_g[v].size());
_g[v].push_back(edge_type(v, u, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({u, u_idx});
_edge_positions.back().push_back({v, v_idx});
return id;
}
void set_edge_alive(int id, bool alive) {
assert(0 <= id && id < _edge_count);
for (int i = 0; i < _edge_positions[id].size; ++i) {
auto [v, idx] = _edge_positions[id].value[i];
_g[v][idx].alive = alive;
}
}
void erase_edge(int id) {
set_edge_alive(id, false);
}
void revive_edge(int id) {
set_edge_alive(id, true);
}
bool is_edge_alive(int id) const {
assert(0 <= id && id < _edge_count);
assert(_edge_positions[id].size != 0);
auto [v, idx] = _edge_positions[id].value[0];
return _g[v][idx].alive;
}
const std::vector<edge_type>& operator[](int v) const {
assert(0 <= v && v < _n);
return _g[v];
}
std::vector<edge_type>& operator[](int v) {
assert(0 <= v && v < _n);
return _g[v];
}
const std::vector<std::vector<edge_type>>& adjacency() const {
return _g;
}
std::vector<std::vector<edge_type>>& adjacency() {
return _g;
}
std::vector<edge_type> edges(bool include_inactive = false) const {
std::vector<edge_type> result;
result.reserve(_edge_count);
std::vector<char> used(_edge_count, false);
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
if (!include_inactive && !e.alive) continue;
if (0 <= e.id && e.id < _edge_count) {
if (used[e.id]) continue;
used[e.id] = true;
}
result.push_back(e);
}
}
return result;
}
Graph reversed() const {
Graph result(_n);
result._edge_count = _edge_count;
result._edge_positions.assign(_edge_count, {});
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
int idx = int(result._g[e.to].size());
result._g[e.to].push_back(edge_type(e.to, e.from, e.cost, e.id, e.alive));
if (0 <= e.id && e.id < _edge_count) result._edge_positions[e.id].push_back({e.to, idx});
}
}
return result;
}
};
} // namespace graph
} // namespace m1une
#line 11 "graph/bellman_ford.hpp"
namespace m1une {
namespace graph {
template <class T>
struct BellmanFordResult {
std::vector<T> dist;
std::vector<int> parent;
std::vector<int> parent_edge;
std::vector<bool> negative;
T inf;
bool has_negative_cycle;
bool reachable(int v) const {
assert(0 <= v && v < int(dist.size()));
return dist[v] != inf;
}
bool affected_by_negative_cycle(int v) const {
assert(0 <= v && v < int(negative.size()));
return negative[v];
}
std::vector<int> path(int t) const {
assert(reachable(t));
assert(!affected_by_negative_cycle(t));
std::vector<int> result;
for (int v = t; v != -1; v = parent[v]) result.push_back(v);
std::reverse(result.begin(), result.end());
return result;
}
};
template <class T>
BellmanFordResult<T> bellman_ford(const Graph<T>& g, const std::vector<int>& sources,
T inf = std::numeric_limits<T>::max() / T(4)) {
int n = g.size();
BellmanFordResult<T> result;
result.dist.assign(n, inf);
result.parent.assign(n, -1);
result.parent_edge.assign(n, -1);
result.negative.assign(n, false);
result.inf = inf;
result.has_negative_cycle = false;
for (int s : sources) {
assert(0 <= s && s < n);
result.dist[s] = T(0);
}
std::vector<int> relaxed_vertices;
for (int iter = 0; iter < n; iter++) {
bool updated = false;
for (int v = 0; v < n; v++) {
if (result.dist[v] == inf) continue;
for (const auto& e : g[v]) {
if (!e.alive) continue;
T nd = result.dist[v] + e.cost;
if (result.dist[e.to] <= nd) continue;
result.dist[e.to] = nd;
result.parent[e.to] = v;
result.parent_edge[e.to] = e.id;
updated = true;
if (iter == n - 1) relaxed_vertices.push_back(e.to);
}
}
if (!updated) break;
}
std::queue<int> que;
for (int v : relaxed_vertices) {
if (result.negative[v]) continue;
result.negative[v] = true;
que.push(v);
}
while (!que.empty()) {
int v = que.front();
que.pop();
for (const auto& e : g[v]) {
if (!e.alive) continue;
if (result.negative[e.to]) continue;
result.negative[e.to] = true;
que.push(e.to);
}
}
for (bool x : result.negative) result.has_negative_cycle = result.has_negative_cycle || x;
return result;
}
template <class T>
BellmanFordResult<T> bellman_ford(const Graph<T>& g, int s, T inf = std::numeric_limits<T>::max() / T(4)) {
return bellman_ford(g, std::vector<int>{s}, inf);
}
} // namespace graph
} // namespace m1une