- 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
- 58 lines of C++ from the credited upstream file 1928.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 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 int minCost(int maxTime, vector<vector<int>>& edges,4 vector<int>& passingFees) {5 const int n = passingFees.size();6 vector<vector<pair<int, int>>> graph(n);7 8 for (const vector<int>& edge : edges) {9 const int u = edge[0];10 const int v = edge[1];11 const int w = edge[2];12 graph[u].emplace_back(v, w);13 graph[v].emplace_back(u, w);14 }15 16 return dijkstra(graph, 0, n - 1, maxTime, passingFees);17 }18 19 private:20 int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst,21 int maxTime, const vector<int>& passingFees) {22 23 vector<int> cost(graph.size(), INT_MAX);24 25 vector<int> dist(graph.size(), maxTime + 1);26 27 cost[src] = passingFees[src];28 dist[src] = 0;29 using T = tuple<int, int, int>; 30 priority_queue<T, vector<T>, greater<>> minHeap;31 minHeap.emplace(cost[src], dist[src], src);32 33 while (!minHeap.empty()) {34 const auto [currCost, d, u] = minHeap.top();35 minHeap.pop();36 if (u == dst)37 return cost[dst];38 if (d > dist[u] && currCost > cost[u])39 continue;40 for (const auto& [v, w] : graph[u]) {41 if (d + w > maxTime)42 continue;43 44 if (currCost + passingFees[v] < cost[v]) {45 cost[v] = currCost + passingFees[v];46 dist[v] = d + w;47 minHeap.emplace(cost[v], dist[v], v);48 } else if (d + w < dist[v]) {49 dist[v] = d + w;50 minHeap.emplace(currCost + passingFees[v], dist[v], v);51 }52 }53 }54 55 return -1;56 }57};58