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 | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
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.