Minimum Number of Refueling Stops in C++

C++Server Side ProgrammingProgramming

Suppose there is a car, that travels from a starting position to a destination which is t miles east of the starting position.

Now along the way, there are many gas stations. So each station[i] represents a gas station that is station[i][0] miles east of the starting position, and that station has station[i][1] liters of gas.

If the car starts with an infinite size of gas tank, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.

When the car reaches one gas station, it may stop and refuel, so now it transfers all the gas from the station into the car. We have to find what is the least number of refueling stops the car must make in order to reach its destination? If it is impossible to reach the destination, return -1.

So, if the input is like Target = 100, startFuel = 20, stations = [10,40],[20,30],[30,20],[60,40], then the output will be 3. So initially there are 10 liters of gas, after reaching the first station, it will transfer 40 liters of gas, so currently there are (0 + 40) = 40 liters gas, then reach to 3rd station now transfer 20 liters of gas, so the current quantity is (20+20) = 40, then reach last station, take 40 liters of gas, so current quantity (10 + 40) = 50, so far we have covered 60 miles, so we have to go 40 miles more to reach destination, there is sufficient gas to reach to the target.

To solve this, we will follow these steps −

  • curr := 0

  • sort the array st

  • Define priority queue pq

  • i := 0, cnt := 0

  • curr := curr + fuel

  • while curr <target, do −

    • (increase cnt by 1)

    • while (i < size of st and st[i, 0] <= curr), do −

      • insert st[i, 1] into pq

      • (increase i by 1)

    • if pq is empty, then −

      • Come out from the loop

    • curr := curr + top element of pq

    • delete element from pq

  • return (if curr >= target, then cnt, otherwise -1)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minRefuelStops(int target, int fuel, vector<vector<int>> &st) {
      int curr = 0;
      sort(st.begin(), st.end());
      priority_queue<int> pq;
      int i = 0;
      int cnt = 0;
      curr += fuel;
      while (curr < target) {
         cnt++;
         while (i < st.size() && st[i][0] <= curr) {
            pq.push(st[i][1]);
            i++;
         }
         if (pq.empty())
            break;
         curr += pq.top();
         pq.pop();
      }
      return curr >= target ? cnt : -1;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{10,40},{20,30},{30,20},{60,40}};
   cout << (ob.minRefuelStops(100, 10, v));
}

Input

100, 10, {{10,40},{20,30},{30,20},{60,40}}

Output

3
raja
Published on 04-Jun-2020 08:35:20
Advertisements