# Find the first circular tour that visits all petrol pumps in C++ Program

Suppose there is a circle, and there are n petrol pumps on the circle. We have two sets of data like −

• The amount of petrol that every petrol pump has
• Distance from one petrol pump to another.

Calculate the first point, from where a truck will be able to complete the circle. Assume for 1 liter petrol, the truck can go 1 unit of distance. Suppose there are four petrol pumps, and the amount of petrol, and distance from the next petrol pump is as like [(4, 6), (6, 5), (7, 3), (4, 5)], the first point from where truck can make a circular tour is 2nd petrol pump. Output should be start = 1 (index of second patrol pump)

This problem can be solved efficiently using queue. Queue will be used to store the current tour. We will insert the first petrol pump into the queue, we will insert petrol pumps till, we either complete the tour, or current amount of petrol becomes negative. If the amount becomes negative, then we keep deleting petrol pumps until it becomes empty.

## Example

Live Demo

#include <iostream>
using namespace std;
class pump {
public:
int petrol;
int distance;
};
int findStartIndex(pump pumpQueue[], int n) {
int start_point = 0;
int end_point = 1;
int curr_petrol = pumpQueue[start_point].petrol - pumpQueue[start_point].distance;
while (end_point != start_point || curr_petrol < 0) {
while (curr_petrol < 0 && start_point != end_point) {
curr_petrol -= pumpQueue[start_point].petrol - pumpQueue[start_point].distance;
start_point = (start_point + 1) % n;
if (start_point == 0)
return -1;
}
curr_petrol += pumpQueue[end_point].petrol - pumpQueue[end_point].distance;
end_point = (end_point + 1) % n;
}
return start_point;
}
int main() {
pump PumpArray[] = {{4, 6}, {6, 5}, {7, 3}, {4, 5}};
int n = sizeof(PumpArray)/sizeof(PumpArray);
int start = findStartIndex(PumpArray, n);
if(start == -1)
cout<<"No solution";
else
cout<<"Index of first petrol pump : "<<start;
}

## Output

Index of first petrol pump : 1