-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbellman_ford.h
More file actions
83 lines (73 loc) · 2.44 KB
/
Copy pathbellman_ford.h
File metadata and controls
83 lines (73 loc) · 2.44 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#ifndef CPP_ALGORITHM_BELLMAN_FORD_H
#define CPP_ALGORITHM_BELLMAN_FORD_H
#include <map>
#include <set>
#include <stdexcept>
#include <vector>
namespace BellmanFord
{
struct Vertex
{
explicit Vertex(const char id)
: id(id), neighbors(std::set<Vertex*>()), predecessor(nullptr), distance(std::numeric_limits<int>::max())
{
}
char id;
std::set<Vertex*> neighbors;
Vertex* predecessor;
int distance;
};
class Graph
{
public:
void AddVertex(Vertex& v);
void AddEdge(Vertex& u, Vertex& v, int weight);
/**
* \brief Bellman-Ford algorithm. Find the shortest path from a source vertex to all other vertices.
* \details A single source shortest path algorithm that can handle negative edge weights.
* It finds the shortest path from a source vertex to all other vertices in a weighted graph.
* \param source source vertex
*/
void BellmanFordAlgorithm(Vertex& source);
std::vector<Vertex*> vertices;
std::vector<std::tuple<Vertex*, Vertex*>> adjacency_list;
std::map<std::pair<char, char>, int> weight_list;
};
}
// ----------------------------------------------------------------------------
inline void BellmanFord::Graph::BellmanFordAlgorithm(Vertex& source)
{
for (int i = 0; i < static_cast<int>(vertices.size()) - 1; ++i)
{
for (auto& [u, v] : adjacency_list)
{
// Relaxation
const auto weight_uv = weight_list.at(std::make_pair(u->id, v->id));
if (v->distance > (u->distance + weight_uv))
{
v->distance = u->distance + weight_uv;
v->predecessor = u;
}
}
}
for (auto& [u, v] : adjacency_list)
{
if (v->distance > (u->distance + weight_list.at(std::make_pair(u->id, v->id))))
{
throw std::runtime_error("Graph has a negative cycle");
}
}
}
// ----------------------------------------------------------------------------
inline void BellmanFord::Graph::AddVertex(Vertex& v)
{
vertices.push_back(&v);
}
// ----------------------------------------------------------------------------
inline void BellmanFord::Graph::AddEdge(Vertex& u, Vertex& v, int weight)
{
adjacency_list.emplace_back(&u, &v);
u.neighbors.insert(&v);
weight_list.insert(std::make_pair(std::make_pair(u.id, v.id), weight));
}
#endif