I'm having trouble implementing a typical dijikstra problem (this one). I'm having a TLE verdict in the last subtask. My submission can be found here. I'm using a set to store the nodes and having a compare function which sorts on the basis of the shortest distances stored in vector d. Everytime a relaxation is encountered, it removes the node, relaxes and changes d[] for that node and enters it again into the set. Can anyone help me get rid of this TLE and tell me why I'm getting one? Thanks in advance.
Use priority_queue instead, it's faster and more useful. A nice implementation can be found at https://cp-algorithms.com/graph/dijkstra_sparse.html
I implemented this version of dijikstra from this source only. I didn't use a priority queue cause I wanted to write a shorter code without all those pairs using a set which I'm more comfortable with. But I'm doing something wrong and I can't figure out what :(
https://codeforces.net/blog/entry/70237
Thanks a lot I didn't know this at all. I'll remember this now onward. After I fixed that compare function to return false when elements are equal though the last subtask is accepted it shows WA on some other ones which was not the case before. I'm confused and pretty sure the problem is with my comp function but now what is it? Thanks in advance.
The reason why I'm so sure that my comparator has a problem is because I submitted the solution with a set of pair of shortest distance and node, and it works fine.
Did you just return false when elements are equal or did you change <= into <? Because you should do the latter.
I changed <= to < here is the code but it's getting WA verdict. Whereas when I use this code I get an AC. I can't figure out what's wrong with using a custom made comparator versus the inbuilt one in set.
Why i am getting tle for two test cases below is the code could someone tell me what to do
Don't visit already visited nodes,use an array of mark[],it should work.
But suppose you get shortest path from another node , so if mark it visited then there may be possibility i missed some small distance then another route
something like this.
use visited array to ensure not visit same node again which is already minimum.