Expedition
Input
* Line 1: A single integer, N
* Lines 2..N+1: Each line contains two space-separated integers describing a fuel stop: The first integer is the distance from the town to the stop; the second is the amount of fuel available at that stop.
* Line N+2: Two space-separated integers, L and P
Output
* Line 1: A single integer giving the minimum number of fuel stops necessary to reach the town. If it is not possible to reach the town, output -1.
Sample Input
4 4 4 5 2 11 5 15 10 25 10
Sample Output
2
题目大意
有n个加油站,每个加油站的加油的油量有限,距离终点都有一个距离。
一个卡车的油箱无限,没走一个单元要消耗一单元的油,问卡车到达终点的最少加多少次油。
解题思路
贪心+优先队列
只有到了加油站才能加油,那我们可以看成只要到过ai这个加油站 就可以加bi的油,那么我们可以把能加的数量都记下来,等到没油了再去加油,相当于在经过加油站的时候加的油。
由于一路上可能经过好多加油站,求的又是最小加油次数,那么我们每次都秀安泽选择能加最大油量的加油站加油,这就用到了优先队列。
代码:
#include <iostream>
#include <queue>
#include <cstdio>
#include <algorithm>
#include <functional> ///greater 函数在里面。
using namespace std;
const int maxn = 1000010;
int n,l,p;///l是长度 p是初始油量
struct Node{
int a,b;
}node[maxn];
priority_queue <int> q;///默认优先级,从大到小,大的先出队
void solve(){
int ans = 0 ,pos = 0, tank = p;///加油次数,当前位置,当前车内油量
for(int i=0;i<n;++i){
int d = node[i].a - pos;///需要走多少米
while(tank - d < 0){///油箱里的油不够跑,那就不断加油
if(q.empty()){
printf("-1\n");
return;
}
tank += q.top();
ans ++;
q.pop();
}
tank -= d;
pos = node[i].a;
q.push(node[i].b);
}
printf("%d\n",ans);
}
int comp(const Node &x,const Node &y){
return x.a < y.a;
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;++i){
scanf("%d%d",&node[i].a,&node[i].b);///题目给的时到终点点的距离
}
scanf("%d%d",&l,&p);
for(int i=0;i<n;++i){
node[i].a = l-node[i].a;///转化为到起点的距离
}
///为了处理方便,把终点也看成加油站
node[n].a = l;
node[n].b = 0;
n++;
sort(node,node+n,comp);
solve();
return 0;
}