File: /home/sanket/bellman1.
cpp Page 1 of 1
#include <bits/stdc++.h>
using namespace std;
struct Edge {
int src, dest, wgt;
};
struct Graph {
int V, E;
vector<Edge> edges;
Graph(int V, int E) : V(V), E(E), edges(E) {}
};
void printArr(const vector<int>& dist) {
cout << "\nVertex Distance from source:\n";
for (int i = 0; i < [Link](); i++)
cout << i << "\t\t" << dist[i] << "\n";
}
void bellmanFord(const Graph& graph, int src) {
int V = graph.V, E = graph.E;
vector<int> dist(V, INT_MAX);
dist[src] = 0;
for (int i = 1; i < V; i++) {
for (const auto& edge : [Link]) {
if (dist[[Link]] != INT_MAX && dist[[Link]] + [Link] < dist[[Link]])
dist[[Link]] = dist[[Link]] + [Link];
}
}
for (const auto& edge : [Link]) {
if (dist[[Link]] != INT_MAX && dist[[Link]] + [Link] < dist[[Link]]) {
cout << "Graph contains negative weight cycle";
return;
}
}
printArr(dist);
}
int main() {
int V, E;
cout << "Enter number of vertices and edges: ";
cin >> V >> E;
Graph graph(V, E);
for (int i = 0; i < E; i++) {
cout << "Enter edge (src dest wgt): ";
cin >> [Link][i].src >> [Link][i].dest >> [Link][i].wgt;
}
bellmanFord(graph, 0);
return 0;
}