Advertisement
mehedi1

Bellman Ford simplest code.cpp

Jul 14th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct edge
  5. {
  6.     int a, b, cost;
  7. };
  8.  
  9. int n, m, v;
  10. vector<edge> e;
  11. const int INF = 1e9;
  12.  
  13. void display(vector<int> &d) {
  14.     for(int i=1;i<=n;++i) {
  15.         printf("%d ",d[i]);
  16.     }
  17. }
  18. int bellman()
  19. {
  20.     vector<int> d (n, INF);
  21.     d[v] = 0;
  22.     for (int i=0; i<n-1; ++i)
  23.         for (int j=0; j<m; ++j)
  24.             if (d[e[j].a] < INF)
  25.                 d[e[j].b] = min (d[e[j].b], d[e[j].a] + e[j].cost);
  26.    
  27.     for(int i=0;i<m;++i) { //check if negative cycle exists
  28.         if(d[e[i].a] + d[e[i].cost] < d[e[i].b]) {
  29.             cout<<"Negative cycle exists\n";
  30.             return 0;
  31.         }
  32.     }
  33.     // display d, for example, on the screen
  34.     display(d);
  35.     return 1;
  36. }
  37. int main() {
  38.     cin>>n>>m;
  39.     for(int i=0;i<m;++i) {
  40.         edge x;
  41.         cin>>x.a>>x.b>>x.cost;
  42.         e.push_back(x);
  43.     }
  44.     cin>>v; //starting vertex
  45.     bellman();
  46.     return 0;
  47. }
  48.  
  49. /*
  50. 4 4
  51.  
  52. 3 2 -10
  53. 4 3 3
  54. 1 4 5
  55. 1 2 4
  56.  
  57. 1
  58. */
  59. /*
  60. 3 3
  61.  
  62. 2 1 -6
  63. 1 3 3
  64. 3 2 2
  65. 1
  66. */
  67.  
  68. /*
  69. BELLMAN-FORD (G, w, s)
  70.     INITIALIZE-SINGLE-SOURCE (G, s)
  71.     for each vertex i = 1 to V[G] - 1 do
  72.         for each edge (u, v) in E[G] do
  73.             RELAX (u, v, w)
  74.     For each edge (u, v) in E[G] do
  75.         if d[u] + w(u, v) < d[v] then
  76.             return FALSE
  77.     return TRUE
  78.  
  79. Analysis:
  80. The initialization in line 1 takes  (v) time
  81. For loop of lines 2-4 takes O(E) time and For-loop of line 5-7 takes O(E) time.
  82. Thus, the Bellman-Ford algorithm runs in O(E) time.
  83. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement