Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include <list>
- #include <stack>
- #include <limits.h>
- using namespace std;
- class AdjListNode
- {
- int v;
- int weight;
- public:
- AdjListNode(int _v, int _w) { v = _v; weight = _w;}
- int getV() { return v; }
- int getWeight() { return weight; }
- };
- class Graph
- {
- int V; // No. of vertices'
- // Pointer to an array containing adjacency lists
- list<AdjListNode> *adj;
- public:
- Graph(int V); // Constructor
- // function to add an edge to graph
- void addEdge(int u, int v, int weight);
- void bell_ford(int src);
- };
- Graph::Graph(int V)
- {
- this->V = V;
- adj = new list<AdjListNode>[V];
- }
- void Graph::addEdge(int u, int v, int weight)
- {
- AdjListNode node(v, weight);
- adj[u].push_back(node); // Add v to u's list
- }
- void Graph::bell_ford(int src)
- {
- int dist[V];
- for (int i = 0; i < V; i++)
- dist[i] = INT_MAX;
- dist[src] = 0;
- for (int u = 0; u < V; u++)
- {
- list<AdjListNode>::iterator i;
- if (dist[u] != INT_MAX)
- {
- for (i = adj[u].begin(); i != adj[u].end(); ++i)
- if (dist[i->getV()] > dist[u] + i->getWeight())
- {
- dist[i->getV()] = dist[u] + i->getWeight();
- }
- }
- }
- cout<<"Vertex\t\tDistance"<<endl;
- for(int i=0;i<V;i++)
- {
- cout<<i<<"\t\t"<<dist[i]<<"\t\t";
- cout<<endl;
- }
- }
- int main()
- {
- Graph g(5);
- g.addEdge(0, 1, -1);
- g.addEdge(0, 2, 4);
- g.addEdge(1, 2, 3);
- g.addEdge(1, 3, 2);
- g.addEdge(1, 4, 2);
- g.addEdge(3, 2, 5);
- g.addEdge(3, 1, 1);
- g.addEdge(4, 3, -3);
- int s = 1;
- cout << "Following are shortest distances from source " << s <<" \n";
- g.bell_ford(s);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement