keymasterviriya1150

Bellman-Ford Code

Apr 18th, 2016
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. vector<int> dist;
  2. // Step 1: Initialize distances
  3.  
  4. dist.assign(V, INT_MAX);
  5.  
  6. dist.[start] = 0;
  7.  
  8. // Step 2: Relax
  9. for (int i = 1; i <= V-1; i++)
  10. {
  11.     for (int j = 0; j < E; j++)
  12.     {
  13.         int u = edge[j].src;
  14.  
  15.         int v = edge[j].dest;
  16.  
  17.         int weight = edge[j].weight;
  18.  
  19.         if ((dist[u] < INT_MAX) && (dist[u] + weight < dist[v]))
  20.             dist[v] = dist[u] + weight;
  21.     }
  22. }
  23. // Step 3: Check negative-weight cycle
  24. for (int i = 0; i < E; i++)
  25. {
  26.     int u = edge[i].src;
  27.  
  28.     int v = edge[i].dest;
  29.  
  30.     int weight = edge[i].weight;
  31.  
  32.     if ((dist[u] != INT_MAX) && (dist[u] + weight < dist[v]))
  33.  
  34.     printf("Graph contains negative weight cycle");
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment