What is purpose of using priority queue in dijkstra algorithm?? In leetcode i solved a problem which requires dijkstra algo,I implemented it by using normal queue and my solution got accepted but when I'm solving CF problem related to dijkstra I got TLE because of using queue [https://mirror.codeforces.com/contest/20/submission/266533020] After that I use priority queue and my solution is accepted [https://mirror.codeforces.com/contest/20/submission/266536259] can anyone explain what is the reason??

A queue is a first-in-first-out data structure — so basically, you insert elements in O(1), and then when you retrieve the elements, you get them back O(1) in the order that you inserted them. For example, in some pseudocode notation:

A priority queue, on the other hand, allows you to insert elements in O(logn), but then the pop method is different — it retrieves the

smallest elementfor example:

Hope this helps, if you have any more questions just let me know

Yes bro you are correct but that is not my question.I'm asking what is the significance of using priority queue over queue in dijkstra algo. Anyway we need to visit all the path's right?? So why we use priority queue.I you still didn't got my doubt just take a random leetcode problem which requires dijkstra algo and submit it by using normal queue.You'll get AC.

But the whole point of Dijkstra's is that it's a greedy algorithm — at every iteration, you take the node with the shortest distance then update the neighbours. How would you even do it with a queue? That would require lots and lots more iterations.

i had the same problem too for solving 20C - Dijkstra?, the normal dijkstra gets TLE on test 28. its because the order of the priority queue approach(if i am correct) is $$$O(E log V)$$$ but the other approach is $$$O(V^2)$$$, if you want to know why:

the priority queue approach: Each time a new vertex is added to the priority queue, or an existing vertex's distance is updated, the priority queue is rearranged, which takes $$$O(log V)$$$ time. The total number of times the priority queue is accessed (push, pop, or update) is proportional to the number of edges, which is $$$O(E)$$$.

the other approach: At each step, the algorithm must search through the entire set of unprocessed vertices to find the vertex with the shortest distance, which takes $$$O(V)$$$ time. The algorithm then updates the distances of all the neighbors of the selected vertex, which takes $$$O(V)$$$ time as well.

Oh! Thank you bro

Strictly speaking, the optimized one is $$$O((E+V)\log V)$$$. You can't throw away the $$$V\log V$$$ term though it always satisfies $$$E>V$$$ for a connected graph.

thanks for completing it.

who has a name like -200? What does it even mean?