Find the first circular tour that visits all petrol pumps

There is a circle, you are given 2 values->

  • The amount of petrol in every petrol pump
  • Distance of petrol pump to the next petrol pump
Calculate the first point from where a truck will be able to complete the circle(truck stops at each pump and has infinite capacity). Assume for 1ltr petrol, the truck can go 1 unit of distance.

Example- there are 4 petrol pumps with amount of petrol and distance to next petrol pump in pairs as {4,3},{6,5},{7,3},{4,5}. The first point from where the truck can make a circular tour is 2nd petrol pump. 

Output should be "start=1" (index of 2nd petrol pump)

An easy solution is to consider ever petrol pump and check whether it can create a circular tour, we use queue to store the values. We first will enqueue first petrol pump to the queue, we keep enqueuing petrol pumps until petrol amount becomes negative, then we dequeue petrol pumps until queue becomes empty.

Code-->

class petrolpump{

    public:

    int petrol;

    int distance;

};

//function returns starting point else returns -1

int tour(petrolpump arr[], int n)

{

    int start=0;  //first petrolpump is the starting point

    int end=1;

    int current_petrol= arr[start].petrol - arr[start].distance;

//run loop to visit all petrol pumps now

while(end!=start || current_petrol<0)

{        //if current amount of petrol becomes 0 or negative then remove starting petrol pump from tour

        while(current_petrol<0 && start!=end)

        {    current_petrol-=arr[start].petrol -arr[start].distance;

              start= (start+1)% n;

              //if 0 is being considered as start again, then theres no solution

               if(start==0)

                    return -1;

        }

    current_petrol+=arr[end].petrol- arr[end].distance;

    end=(end+1)%n;

}

return start;

}

int main()

{

    petrolPump arr[] = {{6, 4}, {3, 6}, {7, 3}};

    int n = sizeof(arr)/sizeof(arr[0]);

    int start = printTour(arr, n);

    (start == -1)? cout<<"No solution": cout<<"Start = "<<start;

    return 0;

}


                

Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)