Problem solution · C++

Minimum Cost to Reach City With Discounts

Minimum Cost to Reach City With Discounts: a C++ solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Heap or priority queue
Source
walkccc LeetCode Solutions
Length
44 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Minimum Cost to Reach City With Discounts, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Cost to Reach City With Discounts · C++C++
Use this to learn the idea, then write your own version.
struct T {  int u;  int d;  int leftDiscounts;}; class Solution { public:  int minimumCost(int n, vector<vector<int>>& highways, int discounts) {    vector<vector<pair<int, int>>> graph(n);    auto compare = [](const T& a, const T& b) { return a.d > b.d; };    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);    unordered_map<int, int> minDiscounts;     for (const vector<int>& h : highways) {      const int city1 = h[0];      const int city2 = h[1];      const int toll = h[2];      graph[city1].emplace_back(city2, toll);      graph[city2].emplace_back(city1, toll);    }     minHeap.emplace(0, 0, discounts);     while (!minHeap.empty()) {      const auto [u, d, leftDiscounts] = minHeap.top();      minHeap.pop();      if (u == n - 1)        return d;      if (const auto it = minDiscounts.find(u);          it != minDiscounts.cend() && it->second >= leftDiscounts)        continue;      minDiscounts[u] = leftDiscounts;      for (const auto& [v, w] : graph[u]) {        minHeap.emplace(v, d + w, leftDiscounts);        if (leftDiscounts > 0)          minHeap.emplace(v, d + w / 2, leftDiscounts - 1);      }    }     return -1;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗