-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathBellmanFord.cpp
More file actions
85 lines (66 loc) · 2.1 KB
/
BellmanFord.cpp
File metadata and controls
85 lines (66 loc) · 2.1 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
84
85
// This algorithm is used to find the shortest path from a single source vertex to all other vertices, even in the presence of negative weight edges. It can detect negative weight cycles.
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
const int INF = INT_MAX;
struct Edge {
int src, dest, weight;
};
class Graph {
public:
int V, E; // Number of vertices and edges
vector<Edge> edges;
Graph(int vertices, int edgesCount) {
V = vertices;
E = edgesCount;
edges.resize(E);
}
void addEdge(int u, int v, int w, int edgeIndex) {
edges[edgeIndex].src = u;
edges[edgeIndex].dest = v;
edges[edgeIndex].weight = w;
}
void bellmanFord(int src) {
vector<int> dist(V, INF);
dist[src] = 0;
for (int i = 0; i < V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int weight = edges[j].weight;
if (dist[u] != INF && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
}
}
}
// Check for negative-weight cycles
for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int weight = edges[j].weight;
if (dist[u] != INF && dist[u] + weight < dist[v]) {
cout << "Negative-weight cycle detected!" << endl;
return;
}
}
cout << "Shortest distances from vertex " << src << ":\n";
for (int i = 0; i < V; i++) {
cout << "Vertex " << i << ": " << dist[i] << "\n";
}
}
};
int main() {
int V, E; // Number of vertices and edges
cin >> V >> E;
Graph g(V, E);
for (int i = 0; i < E; i++) {
int u, v, w;
cin >> u >> v >> w;
g.addEdge(u, v, w, i);
}
int src; // Source vertex for Bellman-Ford
cin >> src;
g.bellmanFord(src);
return 0;
}