C++中的加油站问题
假设有一个圆形,圆上有n个加油站。我们有两组数据,例如:
- 每个加油站拥有的汽油量
- 从一个加油站到另一个加油站的距离。
计算汽车能够完成环形路线的第一个出发点。假设1单位汽油可以行驶1单位距离。例如,有四个加油站,每个加油站的汽油量和到下一个加油站的距离如下:[(4, 6), (6, 5), (7, 3), (4, 5)],汽车可以完成环形路线的第一个出发点是第二个加油站。输出应为 start = 1(第二个加油站的索引)。
这个问题可以使用队列有效地解决。队列将用于存储当前路线。我们将第一个加油站插入队列,直到我们完成路线或当前汽油量变为负数。如果汽油量变为负数,则我们不断删除加油站,直到队列为空。
示例
让我们看下面的实现来更好地理解:
#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;
}输入
[[4, 6], [6, 5], [7, 3], [4, 5]]
输出
Index of first gas station : 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP