Find the shortest path between a source node and destination node in a undirected positive weighted graph. given you can add at max one edge between any two nodes which are not directly connected to each other.?
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 156 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
Find the shortest path between a source node and destination node in a undirected positive weighted graph. given you can add at max one edge between any two nodes which are not directly connected to each other.?
Name |
---|
The first thing to do is to find out if the source and destination are in the same connected components,
1) If they are not, then simply adding an edge between the source and destination with the least possible weight will give the answer.
2) If they are, then adding any edge in that component will create a cycle, which will be of no use. Hence the shortest path between the source and destination will be the answer, which can be computed by bfs.
The given graph is weighted your logic will work fine for unweighted graph but not for weighted graph.
The logic is correct for 1, and for 2 you can use Dijkstra, not bfs.
Counter example:
Let the graph be 1----2-----3
with edge weight of 1---2 = 10 and edge weight of 2---3 = 1
source = 1 destination = 2
here if we add edge between 1--3 of weight = 1 then shortest path = 2
If I get the question correctly now, this show work. If not, then you have to give the link to the original problem.
1) If there is not a direct edge (by direct you meant an edge with one end on source and other in destination?) then simply draw an edge between them with minimum weight.
2) Else, Find a node which is connected to the source but not the destination, (or the destination but not the source) of the minimum possible weight you can and add the edge from that node to the source/destination. In the above case, this would bring the answer to 2.
3)If all nodes have edges between both source and destination,then calculate and store the shortest paths from each node to source and each node to destination. Let them be source[] and destination[] sorted. Then take the smallest two values from each of those two arrays (if they are the same, then take min (source[0] + destination[1], source[1] + destination[0]). Add an edge between these two nodes.