[C++]Expedition
Expedition:
你需要驾驶一辆卡车行驶L单位距离。最开始时,卡车上有P单位的汽油。卡车每开1单位距离需要消耗1单位的汽油。如果在途中车上的汽油耗尽,卡车就无法继续前行,因而无法到达终点。在途中一共有N个加油站。第i个加油站在距离终点Ai单位距离的地方,最多可以给卡车加Bi单位汽油。假设卡车的燃料箱的容量是无限大的,无论加多少油都没有问题。那么请问卡车是否能到达终点?如果可以,最少需要加多少次油?如果可以到达终点,输出最少的加油次数,否则输出-1。
输入格式:
-
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
输出格式:
- 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.
输入:
4
4 4
5 2
11 5
15 10
25 10
输出:
2
解题思路:当卡车到达加油站时,卡车可以选择加油。为使加油次数最少,那么如果此时的油量足够到达终点,那么可以选择不加油。将可以加油的加油站放入优先队列中,当需要加油时,再从优先队列中选择加油站加油。如果优先队列为空,则没有加油站可加油,到不了终点。
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 10000 + 10;
int n, l, p;
struct T{
int a;
int b;
};
int cmp(T a, T b){
return a.a < b.a;
}
int main(){
cin>>n;
T t[maxn];
for(int i = 0; i<n;i ++){
cin>>t[i].a>>t[i].b;
}
cin>>l>>p;
for(int i=0; i<n; i++){
t[i].a = l - t[i].a;
}
sort(t, t+n, cmp);
priority_queue<int> que;
int k = p;
p = 0;
int res = 0;
int left = 0;
while(k < l){
for(int i = left; i<n; i++){
if(k >= t[i].a){
left = i+1;
que.push(t[i].b);
}
}
if(!que.empty()){
p += que.top();
que.pop();
res++;
}
else {
cout<<-1<<endl;
return 0;
}
k += p;
p = 0;
}
cout<<res<<endl;
return 0;
}
来源:CSDN
作者:CGSX
链接:https://blog.csdn.net/s1547156325/article/details/104498010