- 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
- 44 lines of C++ from the credited upstream file 787.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 findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst,4 int k) {5 vector<vector<pair<int, int>>> graph(n);6 7 for (const vector<int>& flight : flights) {8 const int u = flight[0];9 const int v = flight[1];10 const int w = flight[2];11 graph[u].emplace_back(v, w);12 }13 14 return dijkstra(graph, src, dst, k);15 }16 17 private:18 int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst,19 int k) {20 vector<vector<int>> dist(graph.size(), vector<int>(k + 2, INT_MAX));21 22 dist[src][k + 1] = 0;23 using T = tuple<int, int, int>; 24 priority_queue<T, vector<T>, greater<>> minHeap;25 minHeap.emplace(dist[src][k + 1], src, k + 1);26 27 while (!minHeap.empty()) {28 const auto [d, u, stops] = minHeap.top();29 minHeap.pop();30 if (u == dst)31 return d;32 if (stops == 0 || d > dist[u][stops])33 continue;34 for (const auto& [v, w] : graph[u])35 if (d + w < dist[v][stops - 1]) {36 dist[v][stops - 1] = d + w;37 minHeap.emplace(dist[v][stops - 1], v, stops - 1);38 }39 }40 41 return -1;42 }43};44