- 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 2093.cpp.
- The implementation visibly relies on sequence storage, hash lookup, 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.
1struct T {2 int u;3 int d;4 int leftDiscounts;5};6 7class Solution {8 public:9 int minimumCost(int n, vector<vector<int>>& highways, int discounts) {10 vector<vector<pair<int, int>>> graph(n);11 auto compare = [](const T& a, const T& b) { return a.d > b.d; };12 priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);13 unordered_map<int, int> minDiscounts;14 15 for (const vector<int>& h : highways) {16 const int city1 = h[0];17 const int city2 = h[1];18 const int toll = h[2];19 graph[city1].emplace_back(city2, toll);20 graph[city2].emplace_back(city1, toll);21 }22 23 minHeap.emplace(0, 0, discounts);24 25 while (!minHeap.empty()) {26 const auto [u, d, leftDiscounts] = minHeap.top();27 minHeap.pop();28 if (u == n - 1)29 return d;30 if (const auto it = minDiscounts.find(u);31 it != minDiscounts.cend() && it->second >= leftDiscounts)32 continue;33 minDiscounts[u] = leftDiscounts;34 for (const auto& [v, w] : graph[u]) {35 minHeap.emplace(v, d + w, leftDiscounts);36 if (leftDiscounts > 0)37 minHeap.emplace(v, d + w / 2, leftDiscounts - 1);38 }39 }40 41 return -1;42 }43};44