使用 C++ 查詢每個輻射站的最終輻射


假設在一條直線上有 N 個站點。每個站點都具有相同的非負輻射功率。每個站點都可以透過以下方式增加其相鄰站點的輻射功率。

假設站點 i 的輻射功率為 R,它將使第 (i – 1) 個站點的輻射功率增加 R-1,第 (i - 2) 個站點的輻射功率增加 R-2,並將使第 (i + 1) 個站點的輻射功率增加 R-1,第 (i + 2) 個站點的輻射功率增加 R-2,依此類推。例如,如果陣列為 Arr = [1, 2, 3],則輸出將為 3, 4, 4。新的輻射將為 [1 + (2 – 1) + (3 - 2), 2 + (1 – 1) + (3 - 1), 3 + (2 – 1)] = [3, 4, 4]

思路很簡單。對於每個站點 i,都會按照上述方式增加相鄰站點的輻射,直到有效輻射變為負值。

示例

 線上演示

#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-17

71 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.