Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- def read_input():
- return list(map(int, sys.stdin.read().split()))
- # Tries to reach the destination
- # - if destination reachable, returns number of stops
- # - otherwise: returns -1
- def drive(distance, tank_capacity, stops):
- tank = tank_capacity
- distance_travelled = 0
- stops_made = 0
- if tank_capacity < distance - stops[-1]:
- fail(-1)
- # For every stop we are about to move to
- for stop in stops:
- if tank >= stop - distance_travelled: # if we have enough fuel to reach the next stop
- tank, distance_travelled = move(stop, tank, distance_travelled)
- # print("Move: tank: {}, distance_travelled: {}".format(tank, distance_travelled))
- continue
- else:
- if tank_capacity >= stop - distance_travelled: # if refilling will help us reach the next stop
- # print("Refilling: stop: {}, distance_travelled: {}".format(stop, distance_travelled))
- tank = tank_capacity # refill
- stops_made += 1
- tank, distance_travelled = move(stop, tank, distance_travelled)
- else:
- fail(stop)
- if tank == 0 and distance != stop: # if our tank is empty and we need to move
- stops_made += 1 # refill
- return stops_made
- def move(stop, tank, distance_travelled):
- distance_to_travel = stop - distance_travelled
- return (tank - distance_to_travel, stop)
- def fail(stop):
- print("Give up: stop: {}".format(stop))
- return -1
- if __name__ == "__main__":
- data = read_input()
- # data[2] - skipping, we don't care about the number of stops
- distance, tank_capacity, stops = data[0], data[1], data[3:]
- stops_made = drive(distance, tank_capacity, stops)
- print(stops_made)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement