[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;
}