Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- To make sure you catch any kind of bug in raised in your own environment, compile with:
- g++ -Wall -Wextra -Werror -std=c++17 your_code.cpp
- -Wall: Turn on most warnings
- -Wextra: Turn on extra warnings
- -Werror: Treat warnings as errors (forces you to fix them!)
- -std=c++17: Or whatever version you're using
- */
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> bellmanFord(int V, vector<vector<int> > &edges, int src){
- vector<int> distance(V, INT_MAX);
- //Init src distance = 0
- distance[src] = 0;
- // Relax Edges V - 1 times
- for(int k = 0; k < V - 1; k++){
- for(int i = 0; i < edges.size(); i++){
- int u = edges[i][0], v = edges[i][1], w = edges[i][2];
- //If distance of u is INT_MAX, then relaxation can't happen, can't reduce the distance
- //dist[v] = dist[u] + w and dist[u] = INT_MAX
- if(distance[u] != INT_MAX){
- //Relax edge
- if(distance[u] + w < distance[v]){
- distance[v] = distance[u] + w;
- }
- }
- }
- }
- // Try relaxing the edges V - 1 times more, if any changes occur in the distance array
- // Changes means: Negative self loop or Negative weighted cycle
- //Nodes affected: (DIRECTYLY) Nodes directly involved in cycle OR (INDIRECTLY) the nodes which are reachable by the cycle nodes but not directly a part of a cycle
- bool negativeCycle = false;
- for(int k = 0; k < V; k++){
- for(int i = 0; i < edges.size(); i++){
- int u = edges[i][0], v = edges[i][1], w = edges[i][2];
- if(distance[u] != INT_MAX){
- //Nodes getting relaxed in the 2nd run of algorithm are CONTAMINATED by cycle
- if(distance[u] + w < distance[v]){
- negativeCycle = true;
- distance[v] = INT_MAX;
- }
- }
- }
- }
- if(negativeCycle){
- vector<int> res = {-1};
- return res;
- }
- else{
- return distance;
- }
- }
- int main() {
- // your code goes here
- int V, e, src;
- cin >> V >> e;
- vector<vector<int> > edges(e, vector<int>(3));
- for(int i = 0; i < e; i++){
- cin >> edges[i][0] >> edges[i][1] >> edges[i][2];
- }
- cin >> src;
- vector<int> res = bellmanFord(V, edges, src);
- for(int i : res){
- cout << i << " ";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment