Блог пользователя antivenom

Автор antivenom, 11 лет назад, По-английски

Hey guys,I just encountered with a very Interesting and tough problem(at least for me).It is asked to calculate second shortest path from node 1 to N.Can anybody have some idea how to solve this with Dijktra's .In case you want to check if I have tried or not see this(yes,I know I have done nothing special but normal dijktras)

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
11 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Hint: apply 2 dijkstras one from vertex No.1 and the other from vertex No.n and check every edge Maybe that works just maybe xD

»
11 лет назад, скрыть # |
Rev. 3  
Проголосовать: нравится +5 Проголосовать: не нравится

Let Dv, k be the kth shortest path to node v. Suppose we get to v from the 3rd shortest path to node u, then it means Dv, 2 = Du, 3 + [u, v], where [u, v] denotes the road from u to v. But Du, 1 < Du, 2 < Du, 3, so it means both Du, 1 + [u, v] and Du, 2 + [u, v] are less than Du, 3 + [u, v], which is a contradiction, since Dv, 2 would be at least the 3rd shortest path to v. So we don't need to keep track of more than 2 shortest paths for each node.

I coded a Dijkstra storing the two shortest paths for each node, and I believe it should be OK, but I don't have a way to try it out because I can't register at Light OJ.

Here's the code, just in case: C++ Code

UPDATE: Finally, the login data arrived at my e-mail and I was able to test the code. It got AC, so yes, it's the correct idea.

»
11 лет назад, скрыть # |
Rev. 3  
Проголосовать: нравится 0 Проголосовать: не нравится

Implement Dijkstra, but instead of keeping just one array Dist, keep two of them — DistActual and DistSecond. Each time you find a shorter path to the node I, move the value from DistActual[i] to DistSecond[i], and place the new shortest path inside the DistActual[i].

And since before start all the DistActual are equal to INFINITY, if there is no second shortest path, the DistSecond[i] will be equal to INF.