สมมติว่ามีสถานี 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