Minimum Weighted Subgraph With the Required Paths LeetCode solution in Python
1class Solution:2def minimumWeight(self, n, edges, s1, s2, dest):3G1 = defaultdict(list)4G2 = defaultdict(list)5for a, b, w in edges:6G1[a].append((b, w))7G2[b].append((a, w))89def Dijkstra(graph, K):10q, t = [(0, K)], {}11while q:12time, node = heappop(q)13if node not in t:14t[node] = time15for v, w in graph[node]:16heappush(q, (time + w, v))17return [t.get(i, float("inf")) for i in range(n)]1819arr1 = Dijkstra(G1, s1)20arr2 = Dijkstra(G1, s2)21arr3 = Dijkstra(G2, dest)2223ans = float("inf")24for i in range(n):25ans = min(ans, arr1[i] + arr2[i] + arr3[i])2627return ans if ans != float("inf") else -1