Akatsuki13

Bellman Ford

Oct 28th, 2016
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int dist[100];
  6.  
  7. struct Edge
  8. {
  9.     int source, dest, cost;
  10. };
  11.  
  12. Edge edge[100];
  13.  
  14. void print(int n)
  15. {
  16.     printf("Vertex   Distance from Source\n");
  17.  
  18. }
  19.  
  20. void BellmanFord(int v, int e, int source)
  21. {
  22.     for (int i = 0; i<=v; i++) dist[i] = 10000;
  23.     dist[source] = 0;
  24.     for (int i=1; i<=v-1; i++)
  25.     {
  26.         for (int j=0; j<e; j++)
  27.         {
  28.             int u = edge[j].source;
  29.             int v = edge[j].dest;
  30.             int cost = edge[j].cost;
  31.             if (dist[u]!=10000 && dist[u]+cost<dist[v])
  32.                 dist[v] = dist[u] + cost;
  33.         }
  34.     }
  35.     for (int i=0; i<e; i++)
  36.     {
  37.         int u = edge[i].source;
  38.         int v = edge[i].dest;
  39.         int cost = edge[i].cost;
  40.         if (dist[u]!=10000 && dist[u]+cost<dist[v])
  41.             printf("Negative Cycle\n\n");
  42.     }
  43.     printf("\n");
  44.     for (int i=1; i<=v; i++)
  45.         printf("Vertex %d Distance %d\n", i, dist[i]);
  46.     return;
  47. }
  48.  
  49. int main()
  50. {
  51.     int v,e;
  52.     scanf("%d%d", &v, &e);
  53.     int i, j;
  54.     int source, dest, cost;
  55.     for(i=0; i<e; i++)
  56.     {
  57.         scanf("%d%d%d", &source, &dest, &cost);
  58.         edge[i].source = source;
  59.         edge[i].dest = dest;
  60.         edge[i].cost = cost;
  61.     }
  62.     int s;
  63.     cout << "Enter source: ";
  64.     cin >> s;
  65.     BellmanFord(v, e, s);
  66.     return 0;
  67. }
Add Comment
Please, Sign In to add comment