16 int vertexNum, edgeNum;
17 std::vector<Edge> edges;
23 this->edges.reserve(E);
27 void addEdge(
int src,
int dst,
int weight) {
28 static int edgeInd = 0;
29 if (edgeInd < this->edgeNum) {
33 newEdge.weight = weight;
34 this->edges[edgeInd++] = newEdge;
40void print(
const std::vector<int>& dist,
int V) {
41 cout <<
"\nVertex Distance" <<
endl;
42 for (
int i = 0; i < V; i++) {
43 if (dist[i] != INT_MAX)
44 cout << i <<
"\t" << dist[i] <<
endl;
46 cout << i <<
"\tINF" <<
endl;
54 int V =
graph.vertexNum;
55 int E =
graph.edgeNum;
56 std::vector<int> dist;
61 for (
int i = 0; i < V; i++) dist[i] = INT_MAX;
66 for (
int i = 0; i <= V - 1; i++)
67 for (
int j = 0; j < E; j++) {
68 int u =
graph.edges[j].src;
69 int v =
graph.edges[j].dst;
70 int w =
graph.edges[j].weight;
72 if (dist[u] != INT_MAX && dist[u] + w < dist[v])
73 dist[v] = dist[u] + w;
77 for (
int j = 0; j < E; j++) {
78 int u =
graph.edges[j].src;
79 int v =
graph.edges[j].dst;
80 int w =
graph.edges[j].weight;
82 if (dist[u] != INT_MAX && dist[u] + w < dist[v]) {
83 cout <<
"Graph contains negative weight cycle. Hence, shortest "
84 "distance not guaranteed."
99 cout <<
"Enter number of vertices: ";
101 cout <<
"Enter number of edges: ";
104 for (
int i = 0; i < E; i++) {
105 cout <<
"\nEdge " << i + 1 <<
"\nEnter source: ";
107 cout <<
"Enter destination: ";
109 cout <<
"Enter weight: ";
111 G.addEdge(src, dst, weight);
113 cout <<
"\nEnter source: ";
115 BellmanFord(G, gsrc);