Approach
Breadth-first search
For Minimum Weighted Subgraph With the Required Paths, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 65 lines of Java from the credited upstream file 2203.java.
- The implementation visibly relies on sequence storage, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) {3 List<Pair<Integer, Integer>>[] graph = new List[n];4 List<Pair<Integer, Integer>>[] reversedGraph = new List[n];5 6 for (int i = 0; i < n; ++i) {7 graph[i] = new ArrayList<>();8 reversedGraph[i] = new ArrayList<>();9 }10 11 for (int[] edge : edges) {12 final int u = edge[0];13 final int v = edge[1];14 final int w = edge[2];15 graph[u].add(new Pair<>(v, w));16 reversedGraph[v].add(new Pair<>(u, w));17 }18 19 long[] fromSrc1 = dijkstra(graph, src1);20 long[] fromSrc2 = dijkstra(graph, src2);21 long[] fromDest = dijkstra(reversedGraph, dest);22 long ans = MAX;23 24 for (int i = 0; i < n; ++i) {25 if (fromSrc1[i] == MAX || fromSrc2[i] == MAX || fromDest[i] == MAX)26 continue;27 ans = Math.min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]);28 }29 30 return ans == MAX ? -1 : ans;31 }32 33 private static long MAX = (long) 1e10;34 35 private long[] dijkstra(List<Pair<Integer, Integer>>[] graph, int src) {36 long[] dist = new long[graph.length];37 Arrays.fill(dist, MAX);38 39 dist[src] = 0;40 Queue<Pair<Long, Integer>> minHeap =41 new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)) {42 {43 offer(new Pair<>(dist[src], src)); 44 }45 };46 47 while (!minHeap.isEmpty()) {48 final long d = minHeap.peek().getKey();49 final int u = minHeap.poll().getValue();50 if (d > dist[u])51 continue;52 for (Pair<Integer, Integer> pair : graph[u]) {53 final int v = pair.getKey();54 final int w = pair.getValue();55 if (d + w < dist[v]) {56 dist[v] = d + w;57 minHeap.offer(new Pair<>(dist[v], v));58 }59 }60 }61 62 return dist;63 }64}65