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.