adnan_dipta89

Bellman-Ford

Oct 1st, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define MAX 100
  4. typedef long long int ll;
  5. vector< vector<ll> > graph;
  6. ll dist[MAX+1];
  7. ll parent[MAX+1];
  8. ll n, m;
  9. void InitializeSingleSource(ll s)
  10. {
  11.     for(ll i = 1; i <= n; i++)
  12.     {
  13.         dist[i] = INT_MAX;
  14.         parent[i] = 0;
  15.     }
  16.     dist[s] = 0;
  17. }
  18. void Relax(ll u, ll v, ll w)
  19. {
  20.     if(dist[v] > dist[u]+w)
  21.     {
  22.         dist[v] = dist[u]+w;
  23.         parent[v] = u;
  24.     }
  25. }
  26. bool BellmanFord(ll s)
  27. {
  28.     InitializeSingleSource(s);
  29.     for(ll i = 1; i < n; i++)
  30.     {
  31.         for(ll j = 0; j < m; j++)
  32.         {
  33.             ll u = graph[j][0], v = graph[j][1], w =graph[j][2];
  34.             Relax(u,v,w);
  35.         }
  36.     }
  37.     for(ll i = 0; i < m; i++)
  38.     {
  39.         ll u = graph[i][0], v = graph[i][1], w = graph[i][2];
  40.         if(dist[v] > dist[u]+w)
  41.         {
  42.             return false;
  43.         }
  44.     }
  45.     return true;
  46. }
  47.  
  48. int main()
  49. {
  50.     ll s = 4;
  51.     cin >> n >> m;
  52.     for(ll i = 0; i < m; i++)
  53.     {
  54.         ll u, v, w;
  55.         vector<ll> V;
  56.         cin >> u >> v >> w;
  57.         V.push_back(u);
  58.         V.push_back(v);
  59.         V.push_back(w);
  60.         graph.push_back(V);
  61.     }
  62.     if(BellmanFord(s))
  63.     {
  64.         for(ll i = 1; i <= n; i++)
  65.         {
  66.             if(dist[i] == INT_MAX)
  67.             {
  68.                 cout << "There is not route from " << s << " to " << i << endl;
  69.             }
  70.             else
  71.             {
  72.                 cout << "Min distance from " << s << " to ";
  73.                 cout << i << " is " << dist[i] << endl;
  74.             }
  75.         }
  76.         cout << endl;
  77.     }
  78.     else
  79.     {
  80.         cout << "Graph contains negative cycle" << endl;
  81.     }
  82.     return 0;
  83. }
Add Comment
Please, Sign In to add comment