I was trying to solve CSES Shortest Routes I using priority_queue. However, I faced TLE even though I was storing negative of distance in it. After a bit of reading on CP-Algo's Page, they said that
The main difference to the implementation with set is that in many languages, including C++, we cannot remove elements from the priority_queue (although heaps can support that operation in theory).
I have a question regarding this: What happens when pq.pop()
is called? Does it not remove the top element from pq?
PS: CF Rookie here, Please do not downvote. Update: Explained on USACO
Yes. In priority_queue, only the top element can be deleted. But in the set, any element can be deleted.
It was meant that you cannot remove any element other than top element. When distance to vertex is updated you add it to the priority queue, but it may happen that after being added it will get updated again with even smaller distance. But the old one couldn't be removed, so you have to check whether you have handled this vertex before.
I agree. But since the updated new distance is always smaller than the old one, I should get only the latest updated pair (i.e., the smallest distance) from priority_queue and not the older one. Doesn't this reduce the need to check?
No it doesn't, you can see full explanation here
Thanks. I get it now!
glad I helped :)