import heapq def min_refuel_stops(target, start_fuel, stations): # If starting fuel is already greater or equal to target, no need to refuel if start_fuel >= target: return 0 # Create a max heap to store the fuel capacities of stations in # such a way that maximum fuel capacity is at the top of the heap max_heap = [] # Initialize variables for loop i, n = 0, len(stations) stops = 0 max_distance = start_fuel # Loop until the car reach the target or the car is out of fuel while max_distance < target: # If there are still stations and the next one is within range, add its fuel capacity to the max heap if i < n and stations[i][0] <= max_distance: heapq.heappush(max_heap, -stations[i][1]) i += 1 # If there are no more stations and we can't reach the target, return -1 elif not max_heap: return -1 # Otherwise, fill up at the station with the highest fuel capacity and increment stops else: max_distance += -heapq.heappop(max_heap) stops += 1 # Return the number of stops taken return stops # Driver Code def main(): input = ( (3, 3, []), (59, 14, [[9, 12], [11, 7], [13, 16], [21, 18], [47, 6]]), (15, 3, [[2, 5], [3, 1], [6, 3], [12, 6]]), (570, 140, [[140, 200], [160, 130], [310, 200], [330, 250]]), (1360, 380, [[310, 160], [380, 620], [700, 89], [850, 190], [990, 360]]) ) num = 1 for i in input: print(num, ".\tStations : ", i[2], sep="") print("\tTarget : ", i[0]) print("\tStarting fuel : ", i[1]) print("\n\tMinimum number of refueling stops :", min_refuel_stops(i[0], i[1], i[2])) num += 1 print("-" * 100, "\n") if __name__ == "__main__": main()