fluffy_x's blog

By fluffy_x, history, 6 years ago, In English

How to find the shortest path in a weighted graph(**if many then lexicographically smallest**) using Dijkstra? — I am getting WA on 2 test cases - Problem link :Your text to link here... - Although this can be solved using BFS, but I want to know do when the graph is weighted?

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
6 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Let's assume X = 1. Using Dijkstra, calculate the distance Dv from node 1 to node v. For every node u, store Pu, the minimum v over all edges (v, u) such that Dv + w(v, u) = Du. It is easy to find this path now:

std::vector<int> find_path(int v) {
	std::vector<int> ans;
	for(ans.push_back(v); v != 1; ans.push_back(v = p[v]));
	std::reverse(ans.begin(), ans.end());
        return ans;
}
  • »
    »
    6 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    Got it!

  • »
    »
    5 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    Your solution is wrong. Consider this graph:

    6 6 1 2 1 1 4 1 4 3 1 3 6 1 5 6 1 2 5 1

    According to you shortest + lexographically shortest path will be 1 -> 4 -> 3 -> 6 while it should be 1 -> 2 -> 5 -> 6;