Advertisement
karbaev

STL Ford-Bellman

Nov 4th, 2014
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include<iostream>
  2. #include <list>
  3. #include <stack>
  4. #include <limits.h>
  5. using namespace std;
  6. class AdjListNode
  7. {
  8. int v;
  9. int weight;
  10. public:
  11. AdjListNode(int _v, int _w) { v = _v; weight = _w;}
  12. int getV() { return v; }
  13. int getWeight() { return weight; }
  14. };
  15. class Graph
  16. {
  17. int V; // No. of vertices'
  18. // Pointer to an array containing adjacency lists
  19. list<AdjListNode> *adj;
  20. public:
  21. Graph(int V); // Constructor
  22. // function to add an edge to graph
  23. void addEdge(int u, int v, int weight);
  24. void bell_ford(int src);
  25. };
  26. Graph::Graph(int V)
  27. {
  28. this->V = V;
  29. adj = new list<AdjListNode>[V];
  30. }
  31. void Graph::addEdge(int u, int v, int weight)
  32. {
  33. AdjListNode node(v, weight);
  34. adj[u].push_back(node); // Add v to u's list
  35. }
  36. void Graph::bell_ford(int src)
  37. {
  38. int dist[V];
  39. for (int i = 0; i < V; i++)
  40. dist[i] = INT_MAX;
  41. dist[src] = 0;
  42. for (int u = 0; u < V; u++)
  43. {
  44. list<AdjListNode>::iterator i;
  45. if (dist[u] != INT_MAX)
  46. {
  47. for (i = adj[u].begin(); i != adj[u].end(); ++i)
  48. if (dist[i->getV()] > dist[u] + i->getWeight())
  49. {
  50. dist[i->getV()] = dist[u] + i->getWeight();
  51. }
  52. }
  53. }
  54. cout<<"Vertex\t\tDistance"<<endl;
  55. for(int i=0;i<V;i++)
  56. {
  57. cout<<i<<"\t\t"<<dist[i]<<"\t\t";
  58. cout<<endl;
  59. }
  60. }
  61. int main()
  62. {
  63. Graph g(5);
  64. g.addEdge(0, 1, -1);
  65. g.addEdge(0, 2, 4);
  66. g.addEdge(1, 2, 3);
  67. g.addEdge(1, 3, 2);
  68. g.addEdge(1, 4, 2);
  69. g.addEdge(3, 2, 5);
  70. g.addEdge(3, 1, 1);
  71. g.addEdge(4, 3, -3);
  72. int s = 1;
  73. cout << "Following are shortest distances from source " << s <<" \n";
  74. g.bell_ford(s);
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement