From e337c31769738a83f8aaebcd66227a708b4eb3e4 Mon Sep 17 00:00:00 2001 From: Rahul Mishra Date: Sat, 2 Oct 2021 21:16:42 +0530 Subject: [PATCH] Create BellmanFord.cpp Bellman Ford : Minimum Spanning Tree Algorithm --- CPP/BellmanFord.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 CPP/BellmanFord.cpp diff --git a/CPP/BellmanFord.cpp b/CPP/BellmanFord.cpp new file mode 100644 index 0000000..7a65509 --- /dev/null +++ b/CPP/BellmanFord.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; +#define ll long long int +#define pb push_back + +// for 1 based indexing + +map , int > mpx; +vector bellman_ford(vector > adj, int src, int n) +{ + vector dist(n + 1, INT_MAX); + dist[src] = 0; + for (int i = 0; i < n - 1; i++) // Relaxation n-1 times. + { + for (auto it = mpx.begin(); it != mpx.end(); it++) + { + int from = it->first.first, to = it->first.second; + int weight = mpx[ {from, to}]; + if (dist[from] != INT_MAX && (dist[to] > dist[from] + weight)) // 1st condition to check overflow + dist[to] = dist[from] + weight; + } + + } + // Check for negative cycle; + for (auto it = mpx.begin(); it != mpx.end(); it++) + { + int from = it->first.first, to = it->first.second; + int weight = mpx[ {from, to}]; + if (dist[to] > dist[from] + weight) + { + cout << "Negative Cycle Present" << endl; + exit(0); + } + } + return dist; +} + +int main() +{ + int n, m, src; + cin >> n >> m; + vector > adj(n + 1); + for (int i = 0; i < m; i++) { + int a, b, c; + cin >> a >> b >> c; + mpx[ {a, b}] = c; + adj[a].pb(b); + } + //cout << "Enter Source: " << endl; + src = 0; + vector res = bellman_ford(adj, src, n); + for (int i = 0; i < res.size(); i++) + cout << res[i] << " "; + +}