Approach
Breadth-first search
For Minimum Cost to Reach City With Discounts, 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
- 41 lines of Java from the credited upstream file 2093.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 4 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 int minimumCost(int n, int[][] highways, int discounts) {3 record T(int u, int d, int leftDiscounts) {}4 List<Pair<Integer, Integer>>[] graph = new List[n];5 Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::d));6 Map<Integer, Integer> minDiscounts = new HashMap<>();7 8 for (int i = 0; i < graph.length; i++)9 graph[i] = new ArrayList<>();10 11 for (int[] h : highways) {12 final int city1 = h[0];13 final int city2 = h[1];14 final int toll = h[2];15 graph[city1].add(new Pair<>(city2, toll));16 graph[city2].add(new Pair<>(city1, toll));17 }18 19 minHeap.offer(new T(0, 0, discounts));20 21 while (!minHeap.isEmpty()) {22 final int u = minHeap.peek().u;23 final int d = minHeap.peek().d;24 final int leftDiscounts = minHeap.poll().leftDiscounts;25 if (u == n - 1)26 return d;27 if (minDiscounts.getOrDefault(u, -1) >= leftDiscounts)28 continue;29 minDiscounts.put(u, leftDiscounts);30 for (Pair<Integer, Integer> pair : graph[u]) {31 final int v = pair.getKey();32 final int w = pair.getValue();33 minHeap.offer(new T(v, d + w, leftDiscounts));34 if (leftDiscounts > 0)35 minHeap.offer(new T(v, d + w / 2, leftDiscounts - 1));36 }37 }38 return -1;39 }40}41