


Given:
‘N’ = 3, ‘M’ = 3.
‘edges’ =
[[0 1 1],
[1 2 1],
[0 2 3]]
‘src’ = 0, ‘dest’ = 2.
There are two possible paths, that is to go from node-0 to node-2 directly, which will take 2 units of effort, or go from node-0 to node-1 and then node-1 to node-2, which will take 1 unit of effort.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘N,’ where ‘N’ is the number of nodes in the graph, and ‘M’ where ‘M’ is the number of edges.
The next ‘M’ line contains 3 space-separated integers ‘U’, 'V’, and ‘WT’, ‘U’ is the parent node, ‘V’ is the child node and ‘WT’ is the weight of that edge.
The last line contains 2 space-separated integers, ‘src’ and ‘dest’.
For each test case, You are supposed to return an integer that denotes the minimum effort required.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= ‘T’ <= 10
1 <= ‘N’ <= 100
1 <= ‘M’ <= (N*(N + 1))/2
0 <= ‘src’,’dest’ <= N
Time Limit: 1sec.
The idea is to use the Bellman-Ford algorithm, which finds the shortest path from the source node to all the nodes in the graph.
The idea of this algorithm is to maintain a ‘distance’ array which stores the distance between the source node and all of the other nodes and do a process called ‘relaxation’ of all the edges ‘N’ - 1 time, where ‘N’ is the number of nodes.
‘Relaxation’ refers to checking for ‘U’, ‘V’, and ‘WT’ where ‘V’ is the parent node, ‘U’ is the child node and ‘WT’ is the weight of that edge and assigning ‘distance[V]’ = minimum(‘distance[V]’, ‘distance[U]’ + ‘WT’).
After ‘N-1’ relaxations, we check if there is still any possibility to optimize any distance, which implies a negative cycle.
We will use a modified Bellman-Ford for this question, i.e., instead of ‘distance[V]’ = minimum(‘distance[V]’, ‘distance[U]’ + ‘WT’), we will do ‘distance[V]’ = minimum(‘distance[V]’, ‘distance[U]’ * ‘WT’).
The steps are as follows: