- 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
- 53 lines of C++ from the credited upstream file 2714.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 4 int shortestPathWithHops(int n, vector<vector<int>>& edges, int s, int d,5 int k) {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, s, d, k);17 }18 19 private:20 int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst,21 int k) {22 vector<vector<int>> dist(graph.size(), vector<int>(k + 1, INT_MAX));23 24 dist[src][k] = 0;25 using T = tuple<int, int, int>; 26 priority_queue<T, vector<T>, greater<>> minHeap;27 minHeap.emplace(dist[src][k], src, k);28 29 while (!minHeap.empty()) {30 const auto [d, u, hops] = minHeap.top();31 minHeap.pop();32 if (u == dst)33 return d;34 if (dist[u][hops] > d)35 continue;36 for (const auto& [v, w] : graph[u]) {37 38 if (d + w < dist[v][hops]) {39 dist[v][hops] = d + w;40 minHeap.emplace(dist[v][hops], v, hops);41 }42 43 if (hops > 0 && d < dist[v][hops - 1]) {44 dist[v][hops - 1] = d;45 minHeap.emplace(dist[v][hops - 1], v, hops - 1);46 }47 }48 }49 50 throw;51 }52};53