Thursday, 22 January 2015

Dijkstra's Algorithm for shortest path from single source . Using priority queues in c++.

For storing a graph , make an adjacency list . vector < vector < pair <int ,int > > > v . in the pair , the first integer is the node and the second is the weight .
You need to make a priority queue to extract the node with minimum distance from source .
priority_queue<pair<int,int> , vector< pair<int,int> > , compare > q ;
In the pair , the first stores the node and second stores the distance from source .
Now you need to make a compare function for your priority queue .
class compare{
    public:
    bool operator() (  pair<int, int> p1,  pair<int, int> p2 ){
        return p1.second > p2.second;
    }
};

With this your priority queue will extract the node with minimum distance from source .

For storing a graph . Let there be an edge from X to Y with weight W . then for storing it , write :
v[X].push_back ( make_pair(Y,W ) ;

Here is the main dijkstra's algorithm now .

#include<bits/stdc++.h>
using namespace std;
class compare{
    public:
    bool operator() (  pair<int, int> p1,  pair<int, int> p2 ){
        return p1.second > p2.second;
    }
};
int main(){
    priority_queue<pair<int,int> , vector< pair<int,int> > , compare > q ;
    int n;
    cin>>n;
    vector< vector< pair<int,int> > > v;
    v.clear();
    v.resize(n+10);
    int edges;
    cin>>edges;
    while(edges--){
        int x,y,z;
        cin>>x>>y>>z;
        v[x].push_back(make_pair(y,z));
        v[y].push_back(make_pair(x,z));
    }
    int s;
    cin>>s;//source 
    int d[n+1];//array having distances
    for(int i=1;i<=n;i++){
        d[i] = 999999;//initialize all to infinite or a very high value
    }
    d[s] = 0;//distance from source to source is 0
    q.push(make_pair(s,0));
    while(!q.empty()){
        int u = q.top().first;
        q.pop();
        int size = v[u].size();
        for(int i = 0 ; i < size ; i++){
            int vv = v[u][i].first;
            int w = v[u][i].second;
            if(d[vv] > d[u] + w){
                d[vv] = d[u] + w;
                q.push(make_pair(vv,d[vv]));
            }
        }
    }
}

No comments:

Post a Comment