- 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
- 60 lines of C++ from the credited upstream file 2662.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 int minimumCost(vector<int>& start, vector<int>& target,4 vector<vector<int>>& specialRoads) {5 return dijkstra(specialRoads, start[0], start[1], target[0], target[1]);6 }7 8 private:9 int dijkstra(const vector<vector<int>>& specialRoads, int srcX, int srcY,10 int dstX, int dstY) {11 const int n = specialRoads.size();12 13 14 vector<int> dist(specialRoads.size(), INT_MAX);15 using P = pair<int, int>; 16 priority_queue<P, vector<P>, greater<>> minHeap;17 18 19 for (int u = 0; u < n; ++u) {20 const int x1 = specialRoads[u][0];21 const int y1 = specialRoads[u][1];22 const int cost = specialRoads[u][4];23 const int d = abs(x1 - srcX) + abs(y1 - srcY) + cost;24 dist[u] = d;25 minHeap.emplace(dist[u], u);26 }27 28 while (!minHeap.empty()) {29 const auto [d, u] = minHeap.top();30 minHeap.pop();31 if (d > dist[u])32 continue;33 const int ux2 = specialRoads[u][2];34 const int uy2 = specialRoads[u][3];35 for (int v = 0; v < n; ++v) {36 if (v == u)37 continue;38 const int vx1 = specialRoads[v][0];39 const int vy1 = specialRoads[v][1];40 const int vcost = specialRoads[v][4];41 42 const int newDist = d + abs(vx1 - ux2) + abs(vy1 - uy2) + vcost;43 if (newDist < dist[v]) {44 dist[v] = newDist;45 minHeap.emplace(dist[v], v);46 }47 }48 }49 50 int ans = abs(dstX - srcX) + abs(dstY - srcY);51 for (int u = 0; u < n; ++u) {52 const int x2 = specialRoads[u][2];53 const int y2 = specialRoads[u][3];54 55 ans = min(ans, dist[u] + abs(dstX - x2) + abs(dstY - y2));56 }57 return ans;58 }59};60