C++程序查找访问所有加油站的第一个环形路线


假设有一个圆圈,圆圈上有n个加油站。我们有两组数据:

  • 每个加油站拥有的汽油量
  • 从一个加油站到另一个加油站的距离。

计算卡车能够完成环形路线的第一个出发点。假设1升汽油卡车可以行驶1个单位距离。假设有四个加油站,汽油量和到下一个加油站的距离如下所示:[(4, 6), (6, 5), (7, 3), (4, 5)],卡车可以进行环形路线的第一个出发点是第二个加油站。输出应为start = 1(第二个加油站的索引)

这个问题可以使用队列有效地解决。队列将用于存储当前路线。我们将把第一个加油站插入队列,直到我们完成路线或当前汽油量变为负数。如果数量变为负数,则我们将继续删除加油站,直到队列为空。

示例

在线演示

#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[0]);
   int start = findStartIndex(PumpArray, n);
   if(start == -1)
      cout<<"No solution";
   else
      cout<<"Index of first petrol pump : "<<start;
}

输出

Index of first petrol pump : 1

更新于:2019年12月18日

322 次浏览

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.