- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 49 lines of C++ from the credited upstream file 2473.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
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:3 vector<long long> minCost(int n, vector<vector<int>>& roads,4 vector<int>& appleCost, int k) {5 vector<long long> ans;6 vector<vector<pair<int, long>>> graph(n);7 8 for (const vector<int>& road : roads) {9 const int u = road[0] - 1;10 const int v = road[1] - 1;11 const int w = road[2];12 graph[u].emplace_back(v, w);13 graph[v].emplace_back(u, w);14 }15 16 for (int i = 0; i < n; ++i)17 ans.push_back(dijkstra(graph, i, appleCost, k));18 19 return ans;20 }21 22 private:23 long dijkstra(const vector<vector<pair<int, long>>>& graph, int src,24 const vector<int>& appleCost, int k) {25 long ans = LONG_MAX;26 vector<long> dist(graph.size(), LONG_MAX);27 28 dist[src] = 0;29 using P = pair<long, int>; 30 priority_queue<P, vector<P>, greater<>> minHeap;31 minHeap.emplace(dist[src], src);32 33 while (!minHeap.empty()) {34 const auto [d, u] = minHeap.top();35 minHeap.pop();36 if (d > dist[u])37 continue;38 ans = min(ans, appleCost[u] + (k + 1) * d);39 for (const auto& [v, w] : graph[u])40 if (d + w < dist[v]) {41 dist[v] = d + w;42 minHeap.emplace(dist[v], v);43 }44 }45 46 return ans;47 }48};49