Program to find number of starting point from where we can start travelling in Python


Suppose there are n cities numbered from 0 to n-1 and there are n directed roads. We can travel from city i to city (i + 1) % n [0 to 1 to 2 to .... to N - 1 to 0]. We have a car. The capacity of our car's fuel tank is cap unitss. There are fuel[i] units of fuel we can use at the beginning of city i and the car takes cost[i] units of fuel to travel from city i to (i + 1) % n. We have to find how many cities are there from where we can start our car, so that we can travel around all cities and reach the same city where started?

So, if the input is like cap = 3 fuel = [3,1,2] costs = [2,2,2], then the output will be 2 because there are two possible solutions.

  • we can start from city 0, fills the tank with 3 units of fuel, and use 2 units of fuel to travel to city 1. Tank has one unit left. After taking 1 unit of fuel at city 1, car has 2 units of fuel and we can travel to city 2 by using 2 units of fuel. The fuel tank is now empty. After refueling 2 gallon of fuel at city 2, we then travel back to city 0 by using 2 gallons of fuel.

  • We can start from city 2, fill the car with 2 units of fuel, and travels to city 0. Then after refueling 3 gallons of fuel from city 0, we then travel to city 1, and we have 1 unit of fuel. We can then refuel 1 unit of fuel at City 1, and now have 2 units of fuel and travel to city 2.

However, we cannot start from city 1, there is only 1 unit of fuel is present, but travelling to city 2 requires 2 gallons.

To solve this, we will follow these steps −

  • n := size of fuel
  • req := an array of size n and fill with 0
  • for k in range 0 to 1, do
    • for i in range n-1 to 0, decrease by 1, do
      • nexti :=(i + 1) mod n
      • req[i] := maximum of 0 and req[nexti] + costs[i] - fuel[i]
      • if minimum of (req[i] + fuel[i] and cap) - costs[i] < req[nexti], then
        • return 0
  • return count number of 0s in r

Example

Let us see the following implementation to get better understanding −

def solve(cap, fuel, costs):
   n = len(fuel)
   req = [0] * n

   for k in range(2):
      for i in range(n-1, -1, -1):
         nexti = (i + 1) % n
         req[i] = max(0, req[nexti] + costs[i] - fuel[i])
         if min(req[i] + fuel[i], cap) - costs[i] < req[nexti]:
            return 0
   return sum(1 for r in req if r == 0)

cap = 3
fuel = [3,1,2]
costs = [2,2,2]
print(solve(cap, fuel, costs))

Input

3, [3,1,2], [2,2,2]

Output

2

Updated on: 23-Oct-2021

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements