-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbellmanalg.cpp
More file actions
113 lines (88 loc) · 2.71 KB
/
bellmanalg.cpp
File metadata and controls
113 lines (88 loc) · 2.71 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
using namespace std;
class BellmanFord {
int **edges, *dist, *parent, vertices, edgesCount;
public:
BellmanFord(int v, int e) {
vertices = v;
edgesCount = e;
edges = new int*[edgesCount];
for (int i = 0; i < edgesCount; i++)
edges[i] = new int[3];
dist = new int[vertices];
parent = new int[vertices];
}
void inputEdges() {
cout << "Enter edges in the format (u v w) where u and v are vertices and w is weight:\n";
for (int i = 0; i < edgesCount; i++) {
cin >> edges[i][0] >> edges[i][1] >> edges[i][2];
}
}
void bellmanFord(int src) {
for (int i = 0; i < vertices; i++) {
dist[i] = 9999;
parent[i] = -1;
}
dist[src] = 0;
for (int i = 0; i < vertices - 1; i++) {
for (int j = 0; j < edgesCount; j++) {
int u = edges[j][0];
int v = edges[j][1];
int w = edges[j][2];
if (dist[u] != 9999 && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
parent[v] = u;
}
}
}
for (int j = 0; j < edgesCount; j++) {
int u = edges[j][0];
int v = edges[j][1];
int w = edges[j][2];
if (dist[u] != 9999 && dist[u] + w < dist[v]) {
cout << "Graph contains a negative weight cycle!\n";
return;
}
}
}
void printPath(int j) {
if (parent[j] == -1)
return;
printPath(parent[j]);
cout << " -> " << j;
}
void displayDistances() {
cout << "Vertex \t Distance \t Path" << endl;
for (int i = 0; i < vertices; i++) {
cout << i << "\t" << dist[i] << "\t";
cout << "" << i;
printPath(i);
cout << "\n";
}
}
~BellmanFord() {
for (int i = 0; i < edgesCount; i++)
delete[] edges[i];
delete[] edges;
delete[] dist;
delete[] parent;
}
};
int main() {
int v, e, src;
cout << "Enter number of vertices and edges: ";
cin >> v >> e;
BellmanFord bf(v, e);
bf.inputEdges();
cout << "Enter source vertex: ";
cin >> src;
bf.bellmanFord(src);
bf.displayDistances();
return 0;
}
/*This is the Bellman-Ford algorithm implementation in C++. It:
Accepts user input for the number of vertices and edges.
Uses dynamic memory allocation for storing edges and distances.
Detects negative weight cycles in the graph.
Displays shortest distances and paths from the source.
Let me know if you need modifications!*/