# Gas Station in C++

C++Server Side ProgrammingProgramming

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

• The amount of gas that every gas stations has
• Distance from one gas stations to another.

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

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

## Example

Let us see the following implementation to get a better understanding −

Live Demo

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

## Input

[[4, 6], [6, 5], [7, 3], [4, 5]]

## Output

Index of first gas station : 1
Published on 31-Jan-2020 06:39:59