vendredi 29 mai 2015

Dijsktra algorithm in C++

I have a number of source vertices and need to find paths using Dijkstra from these source vertices. For doing so I wrote the following program. As path from each source vertex is computed independently of the other, therefore I parallelized the code using openmp. However, the program seems to be running in an infinite loop, can someone please tell me as to where am I going wrong. Is there any other way by which I may parallelize the execution of Dijsktra algorithm for finding paths from a number of source vertices.

#include <iostream>
#include <set>
#include <vector>
#include <map>
using namespace std;

typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
typedef vector<vii> vvii;

const int MAX = 1001;
const int MAXINT = 1000000000;

int n;
vvii G(MAX);

void Dijkstra(int s,vi& D)
{
    set<ii> Q;
    D[s] = 0;
    Q.insert(ii(0,s));

    while(!Q.empty())
    {
        ii top = *Q.begin();
        Q.erase(Q.begin());
        int v = top.second;
        int d = top.first;
        for (vii::const_iterator it = G[v].begin(); it != G[v].end(); it++)
        {
            int v2 = it->first;
            int cost = it->second;
            if (D[v2] > D[v] + cost)
            {
                if (D[v2] != 1000000000)
                {
                    Q.erase(Q.find(ii(D[v2], v2)));
                }
                D[v2] = D[v] + cost;
                Q.insert(ii(D[v2], v2));
            }
        }
    }
}        
int main()
{
    vector<unsigned> sourceNodes; //intializing source nodes from a separate file
    map<unsigned,vector<int> > mapSourceDistance;
    #pragma omp parallel for    
    for(unsigned i=0;i<sourceNodes.size();i++)
    //for(auto it : rankingNodes)
    {       
        vi D(MAX, MAXINT);
        Dijkstra(sourceNodes[i],D);
        #pragma omp critical
        mapSourceDistance[sourceNodes[i]]=D;
    }    
}

gcc which I am using is gcc-4.8

Aucun commentaire:

Enregistrer un commentaire