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

更新於: 2020年4月28日

489 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.