Suppose we have to plan a road trip that involves visiting various cities from different countries. We have a list of roads 'R', where each element is described as (x, y, cost). x signifies the starting city of the road, y signifies the destination city of the road, and cost signifies the cost of traveling by that road. We also have a list 'C' where each element is a country and an element contains the cities of that country. Now, we also have a starting city 's' and a destination city 'e', and we want to travel to the destination city from the source city. Given all this information, we have to find out the minimum number of intercountry travels we have to make to complete the trip and also the total cost of travel for the trip. We have to print these two values as output.
So, if the input is like R = [[0, 1, 2],[1, 2, 2], [0, 2, 3], [1, 3, 3]], C = [[0], [1], [2, 3]], s = 0, e = 3, then the output will be (2,5).
So, to travel from 0 to 3 we take the path 0->1->3. The roads taken in this path are [0, 1, 2], and [1, 3, 3]. Thus, the total country-to-country travel is 2 and the total cost is 2 + 3 = 5.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from collections import defaultdict from heapq import heappush, heappop def solve(R, C, s, e): cont = defaultdict(int) for idx, item in enumerate(C): for k in item: cont[k] = idx adj_list = defaultdict(list) for a, b, wt in R: if cont[a] != cont[b]: wt += 10 ** 10 adj_list[a].append((b, wt)) distance = defaultdict(lambda: 10 ** 20) distance[s] = 0 visited = set() t = [(0, s)] while t: d, c = heappop(t) if c in visited: continue visited.add(c) for j, wt in adj_list[c]: if distance[j] > d + wt: distance[j] = d + wt heappush(t, (d + wt, j)) return distance[e] // 10 ** 10, distance[e] % 10 ** 10 print(solve([[0, 1, 2],[1, 2, 2],[0, 2, 3], [1, 3, 3]], [[0],[1],[2, 3]], 0, 3))
[[0, 1, 2],[1, 2, 2],[0, 2, 3], [1, 3, 3]], [[0],[1],[2, 3]], 0, 3
(2, 5)