题意:有一辆漏油的卡车要开到一个城镇,每行驶一个单位距离,油箱就会漏一单位的油(不考虑耗油),行驶过程中有N个加油站,每个加油站距离城镇dis的单位距离,并可以加fuel的单位油量已知距离为L,假设油箱的油量没有上限。油箱当前油量为P,起点距离终点L米,问卡车最少可以加几次油就可以到达终点。
题解:这里给出的是距离终点的加油站距离,要先转换一下。我们可以把终点也当做一个加油站,即距离为0,加油也为0。先将加油站按照距离终点的长度从小到大排序(这里可以借助优先队列)q1,然后再创建一个按加油站从大到小排序的优先队列q2,每经过一个加油站便把其入队q2,当车子的油量为0时,每当油量不足时便取队列中的头元素加上去,直到可以到达下一个加油站。
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdio>
using namespace std;
const int maxn = 10000;
struct stop{
int dis, fuel;
}s[10010];
struct cmp1{
bool operator () (stop& i, stop& j) {
return i.fuel < j.fuel;
}
};
struct cmp2{
bool operator () (stop& i, stop& j) {
return i.dis > j.dis;
}
};
int main(){
int n,l,p;
cin >> n;
for(int i = 0; i < n; ++i) cin >> s[i].dis >> s[i].fuel;
cin >> l >> p;
priority_queue<stop, vector<stop> , cmp2> q;
priority_queue<stop ,vector<stop> ,cmp1> que;
q.push(stop{l,0});
for(int i = 0; i < n; ++i) {
s[i].dis = l - s[i].dis;
q.push(s[i]);
}
// int m = -1;
int cnt = 0;
while(!q.empty() && p < l){
stop t = q.top();
//cout << t.dis <<" " << t.fuel << endl;
if(t.dis <= p){
que.push(t); q.pop();
}
else{
while(!que.empty() && p < t.dis){
stop tmp = que.top(); que.pop();
if(tmp.fuel == 0) continue;
p += tmp.fuel;
cnt++;
//cout << p << endl;
}
if(p < t.dis) break;
}
}
if(p >= l) cout << cnt << endl;
else puts("-1");
return 0;
}