-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBellman_ford.cpp
More file actions
69 lines (61 loc) · 1.91 KB
/
Bellman_ford.cpp
File metadata and controls
69 lines (61 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "Bellman_ford.h"
Bellman_ford::Bellman_ford(const Edge_weighted_digraph& digraph, int s)
: _dist_to(digraph.num_vertices(), _inf),
_edge_to(digraph.num_vertices()),
_on_queue(digraph.num_vertices()),
_queue{}
{
_dist_to[s] = 0.0;
// Bellman-Ford algorithm
_queue.push_back(s);
_on_queue[s] = true;
while (!_queue.empty() && !has_negative_cycle()) {
auto v = _queue.front();
_queue.pop_front();
_on_queue[v] = false;
_relax(digraph, v);
}
}
double Bellman_ford::distance_to(int v)
{
if (has_negative_cycle()) { throw std::runtime_error{"Negative cost cycle exists"}; }
return _dist_to[v];
}
std::vector<Directed_edge> Bellman_ford::path_to(int v)
{
if (has_negative_cycle()) { throw std::runtime_error{"Negative cost cycle exists"}; }
if (!has_path_to(v)) { return {}; }
std::vector<Directed_edge> path;
for (auto e = _edge_to[v]; e != _default; e = _edge_to[e.from()]) { path.push_back(e); }
return path;
}
void Bellman_ford::_relax(const Edge_weighted_digraph& digraph, int v)
{
for (auto& e : digraph.adjacent(v)) {
auto w = e.to();
if (_dist_to[w] > _dist_to[v] + e.weight()) {
_dist_to[w] = _dist_to[v] + e.weight();
_edge_to[w] = e;
if (!_on_queue[w]) {
_queue.push_back(w);
_on_queue[w] = true;
}
}
if (_cost++ % digraph.num_vertices() == 0) {
_find_negative_cycle();
if (has_negative_cycle()) { return; }
}
}
}
void Bellman_ford::_find_negative_cycle()
{
auto num_vertices = _edge_to.size();
Edge_weighted_digraph spt{num_vertices};
for (auto v = 0; v < num_vertices; ++v) {
if (_edge_to[v] != _default) {
spt.add_edge(_edge_to[v]);
}
}
Edge_weighted_directed_cycle finder{spt};
_cycle = finder.cycle();
}