templates/bellman-ford.cpp
compilable
$cat templates/bellman-ford
Bellman-Ford
Shortest path with negative edge weights and negative cycle detection in O(V*E).
#bellman-ford#shortest-path#negative-weights#negative-cycle
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1e18;
struct Edge { int u, v; ll w; };
vector<Edge> edges;
vector<ll> dist;
void bellmanFord(int src, int n) {
dist.assign(n + 1, INF);
dist[src] = 0;
for (int i = 0; i < n - 1; i++)
for (auto &[u, v, w] : edges)
if (dist[u] < INF)
dist[v] = min(dist[v], dist[u] + w);
}
bool hasNegativeCycle() {
for (auto &[u, v, w] : edges)
if (dist[u] < INF && dist[v] > dist[u] + w)
return true;
return false;
}26 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Bellman-Ford
Single-source shortest path supporting negative edge weights, plus negative cycle detection.