
1. Start from node 1 and move to the next unvisited node having the highest weight.
2. If two or more nodes have the same weight, move to the node, which takes less time to move to another node.
3. If there are no adjacent unvisited nodes at a point, then you have to traverse back to the previous node from where you came to the present node for the first time.
4. Repeat the above process till all the nodes are visited.
Let the number of nodes be: 3
Let there be an edge between nodes 1 and 3 and between nodes 1 and 2.
Let the time required to reach from node 1 to 3 be 2 units and node 1 to 2 be 4 units.
Let the weights of each node be: [0, 1, 1]
The graph for above will be:
We start from node 1. Its adjacent nodes are: {2, 3} out of which both nodes have the same weights, but the time needed to reach node 3 is less so we first move to node 3, so the first arrival time at node 3 will be 2 units.
We then move to node 3 whose adjacent nodes are: {1} which is already visited.
We move back to node 1, which takes 2 units of time. 2 + 2 = 4 units.
We then move to node 2 from node 1, which takes 4 + 4 = 8 units.
Hence the answer is [0, 8, 2].
The first line of input contains an integer ‘T’, the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, representing the number of nodes and, number of edges, respectively.
Each test case’s next ‘M’ lines contain two single space-separated integers, ‘X', 'Y', and ‘D’, which signifies an edge between ‘X’ and ‘Y’, and the time taken to travel between the two nodes, respectively.
The ‘M’ + 1 line of each test case contains ‘N’ single space-separated integers, representing the weight of each node.
For each test case, print 'N' space-separated integers representing the time arrival at each node for the first time.
Print output of each test case in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^3
N - 1 <= M <= min(N* (N - 1) / 2, 10^3)
1 <= X, Y <= N
1 <= WEIGHT[i] <= 10^9
1 <= D <= 10^6
Time Limit: 1 sec
The basic idea is to use a depth-first search to travel the nodes. We travel all the nodes of the adjacent nodes to find the node with maximum weight, and if weight is equal, we check for the least time required to travel between the nodes. We also need to store the time to travel between the current node and the previous node to add when we travel back to any of the nodes.
Here is the algorithm :
DFS(‘GRAPH’, ‘VISITED’, ‘WEIGHT’, ‘RES’, U, ‘D’, ‘PRE’) (where ‘U’ is the current node, ‘PRE’ is the time taken to reach the current node from the previous node).