0

I wrote a slightly modified Dijkstra algorithm using a priority queue that stores pairs of numbers. When i declare it as

priority_queue < pair<int,int> > Q;

it is painfully slow- 268 ms. On the other hand, if i write it as

priority_queue < pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>> > Q;

it is as fast as it should be- 12ms.

The code for the algorithm is the following

void dijkstra(int inode){
    for(int i=1;i<=n;++i)dp[inode][i]=inf;
    Q.push({0,v[inode]});
    dp[inode][v[inode]]=0;
    while(!Q.empty()){
        int node=Q.top().second;
        int dist=Q.top().first;
        Q.pop();
        if(dp[inode][node]<dist)continue;
        for(auto edge: G[node]){
            if(dp[inode][edge.first]>dist+edge.second){
                dp[inode][edge.first]=dist+edge.second;
                Q.push({dp[inode][edge.first],edge.first});
            }
        }
    }
}

What am i missing ? Where is that difference coming from?

  • First questions first: Are you compiling with optimizations turned on? Did you try to profile to see what was longer in the first version? – Borgleader Oct 13 '17 at 20:49
  • 1
    I suspect your results are biased towards the example graph you are using to make the test. In fact all what you are changing is the comparison function. – skypjack Oct 13 '17 at 20:49
  • I tried to use multiple graphs and the results are similar. What makes the comparison functions different? – Andrei Mihailescu Oct 13 '17 at 20:52
  • The fact that you use `std::greater` in place of `std::less` (the default type for the comparison function) in your last attempt. The rest is due to the way a priority queue works. – skypjack Oct 13 '17 at 20:57
  • So std::less is slower at comparing pairs than std::greater ? – Andrei Mihailescu Oct 13 '17 at 20:59
  • @AndreiMihailescu, no, but when using std::less there is more comparisons for your dataset. Randomise your input and to get a fair test – Werner Erasmus Oct 13 '17 at 21:06
  • 1
    `std::less` and `std::greater` have the same performance but their meanigs are different. Changing from `less` to `greater` makes your algorithm do a totally different thing. – navyblue Oct 16 '17 at 01:45

0 Answers0