【POJ 2431 --- Expedition】
Description
A group of cows grabbed a truck and ventured on an expedition deep into the jungle. Being rather poor drivers, the cows unfortunately managed to run over a rock and puncture the truck’s fuel tank. The truck now leaks one unit of fuel every unit of distance it travels.
To repair the truck, the cows need to drive to the nearest town (no more than 1,000,000 units distant) down a long, winding road. On this road, between the town and the current location of the truck, there are N (1 <= N <= 10,000) fuel stops where the cows can stop to acquire additional fuel (1…100 units at each stop).
The jungle is a dangerous place for humans and is especially dangerous for cows. Therefore, the cows want to make the minimum possible number of stops for fuel on the way to the town. Fortunately, the capacity of the fuel tank on their truck is so large that there is effectively no limit to the amount of fuel it can hold. The truck is currently L units away from the town and has P units of fuel (1 <= P <= 1,000,000).
Determine the minimum number of stops needed to reach the town, or if the cows cannot reach the town at all.
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
Hint
INPUT DETAILS:
The truck is 25 units away from the town; the truck has 10 units of fuel. Along the road, there are 4 fuel stops at distances 4, 5, 11, and 15 from the town (so these are initially at distances 21, 20, 14, and 10 from the truck). These fuel stops can supply up to 4, 2, 5, and 10 units of fuel, respectively.
OUTPUT DETAILS:
Drive 10 units, stop to acquire 10 more units of fuel, drive 4 more units, stop to acquire 5 more units of fuel, then drive to the town.
- 解题思路
通过遍历,在经过加油站时,往优先队列里加入可用油量。
当油箱空了时:
- 如果优先队列为空,则无法到达终点。
- 如果不为空,则取出优先队列中最大的元素,并给卡车加油,然后继续遍历。
AC代码:
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
#define MAXN 10010
int n,l,p;
struct Node
{
int a,b;
}arr[MAXN];
bool compare(Node &a,Node &b)
{
return a.a<b.a;
}
int main()
{
cin >> n;
for(int i=1;i<=n;i++)
{
cin >> arr[i].a >> arr[i].b;
}
sort(arr+1,arr+n+1,compare);//根据与城镇的距离排序。
cin >> l >> p;
priority_queue<int> q;
int ans=0,pos=l,tank=p;
arr[0].a=0;
arr[0].b=0;
for(int i=n;i>=0;i--)
{
int x=pos-arr[i].a;
while(tank-x<0)
{
if(q.empty())
{
cout <<"-1"<<endl;
return 0;
}
tank+=q.top();
q.pop();
ans++;
}
tank-=x;
pos=arr[i].a;
q.push(arr[i].b);
}
cout << ans << endl;
return 0;
}