Approach
Breadth-first search
For Minimum Cost to Buy Apples, 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
- 51 lines of Java from the credited upstream file 2473.java.
- The implementation visibly relies on sequence storage, 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 long[] minCost(int n, int[][] roads, int[] appleCost, int k) {3 long[] ans = new long[n];4 List<Pair<Integer, Integer>>[] graph = new List[n];5 Arrays.setAll(graph, i -> new ArrayList<>());6 7 for (int[] road : roads) {8 final int u = road[0] - 1;9 final int v = road[1] - 1;10 final int w = road[2];11 graph[u].add(new Pair<>(v, w));12 graph[v].add(new Pair<>(u, w));13 }14 15 for (int i = 0; i < n; ++i)16 ans[i] = dijkstra(graph, i, appleCost, k);17 18 return ans;19 }20 21 private long dijkstra(List<Pair<Integer, Integer>>[] graph, int i, int[] appleCost, int k) {22 long ans = Long.MAX_VALUE;23 long[] dist = new long[graph.length];24 Arrays.fill(dist, Long.MAX_VALUE);25 26 dist[i] = 0;27 Queue<Pair<Long, Integer>> minHeap =28 new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)) {29 { offer(new Pair<>(dist[i], i)); } 30 };31 32 while (!minHeap.isEmpty()) {33 final long d = minHeap.peek().getKey();34 final int u = minHeap.poll().getValue();35 if (d > dist[u])36 continue;37 ans = Math.min(ans, appleCost[u] + (k + 1) * d);38 for (Pair<Integer, Integer> pair : graph[u]) {39 final int v = pair.getKey();40 final int w = pair.getValue();41 if (d + w < dist[v]) {42 dist[v] = d + w;43 minHeap.offer(new Pair<>(dist[v], v));44 }45 }46 }47 48 return ans;49 }50}51