卡車距離終點 L,初始油量 P。路徑上有 N 個加油站,每站距離終點 dis、提供油量 fuel。卡車每單位距離消耗 1 單位油,油箱無容量上限。求到達終點最少加油次數,不可達輸出 -1。
dis = L - dis,並按距離升序排序。為了最小化加油次數,每次應選擇當前可達範圍內油量最大的站點加油。最大堆恰好提供此操作,貪心策略最優。
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int MAX = 1e4 + 5;
struct Stop { int dis, fuel; } s[MAX];
bool cmp(Stop a, Stop b) { return a.dis < b.dis; }
int main() {
int n, l, p;
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < n; i++) scanf("%d %d", &s[i].dis, &s[i].fuel);
scanf("%d %d", &l, &p);
for (int i = 0; i < n; i++) s[i].dis = l - s[i].dis;
s[n].fuel = 0; s[n++].dis = l; // 終點入隊
sort(s, s + n, cmp);
priority_queue<int> q;
int ans = 0, pos = 0, fuel = p;
for (int i = 0; i < n; i++) {
int d = s[i].dis - pos;
while (fuel < d) {
if (q.empty()) { printf("-1\n"); goto END; }
fuel += q.top(); q.pop(); ans++;
}
fuel -= d;
q.push(s[i].fuel);
pos = s[i].dis;
}
printf("%d\n", ans);
END: ;
}
return 0;
}
goto END 簡化多層循環跳出,實際可用標誌變量替代。