题意
一辆卡车,油箱体积无限, 要走L公里,初始有P升汽油,每前进一公里要一升汽油,途中有n个加油站,输入每个加油站到终点的距离以及可加多少升油,若能到达终点,最少要加几次油,否则输出-1
解法
其实这道题在《挑战程序设计竞赛》上有,在74页,讲的很好
当我们路过加油站的时候,我们可加可不加,把它当成我们的备用能源,走到没油了我们就启用备用能源,先用哪个呢,肯定是量最大的那个啦,反正都是加一次,为什么不加多一点,如果不够就再加,如果油量为0,而且也没备用,那就gg了,输出-1
代码
#include <iostream>
#include <cmath>
#include <queue>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 100000 + 100;
struct node {
int dis, add;
}p[maxn];
inline bool cmp(node a, node b) {
return a.dis < b.dis;
}
int main() {
int n;
while(scanf("%d", &n) != EOF ) {
memset(p, 0, sizeof(p));
for(int i=1; i<=n; ++i) {
scanf("%d%d", &p[i].dis, &p[i].add);
}
int L, P;
scanf("%d%d", &L, &P);
//原本输入的是加油站到终点的距离,为了方便处理,改成到起点的距离
for(int i=1; i<=n; ++i) p[i].dis = L - p[i].dis;
//把终点也当加油站,到起点距离L, 可加油0L
p[n+1].dis = L;
p[n+1].add = 0;
n++;
sort(p+1, p+1+n, cmp);
priority_queue <int> q;
//ans: 加油次数 pos:当前位置 tank:当前汽油量
int ans = 0;
int pos = 0;
int tank = P;
int flag = 1;
for(int i=1; i<=n; ++i) {
//接下来要前进的距离
int d = p[i].dis - pos;
while(tank - d < 0) {
if(q.empty()) {
printf("-1\n");
flag = 0;
break;
}
tank += q.top();
q.pop();
ans++;
}
if(!flag) break;
tank -= d;
pos = p[i].dis;
q.push(p[i].add);
}
if(flag) printf("%d\n", ans);
}
return 0;
}