POJ2431 -- 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.

Analysis

在《挑战程序设计竞赛(第二版)》中看到这道题,我们可以稍微变换一下思考方式,在途中只有经过加油站才可以加油。但是如果认为随时可以加油(感觉与Ants有些类似),那么就可以在需要加油时就认为是之前在加油站加的油就可以了。为了高效进行上述操作,我们可以使用从大到小的优先队列。当经过加油站时,往优先队列里加入Bi,当燃料箱空了时,如果优先队列也空了,则无法到达终点。否则取出优先队列队首元素来加油。

Code

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define N 10011
using namespace std;
struct site{
	int a,b;
}A[N];
int n,L,P;
bool cmp(site & x,site & y){
	return x.a < y.a;
}
void solve(){
	priority_queue<int> Q;
	A[++n].a = L;
	A[n].b = 0;
	sort(A,A+n,cmp);
	int ans = 0,pos = 0,tank = P;
	for(int i = 0;i < n;++i){
		A[i].a = L - A[i].a;
		int d = A[i].a - pos;
		while(tank - d < 0){
			if(Q.empty()){
				printf("-1\n");
				return;
			}
			tank += Q.top();
			Q.pop();
			++ans;
		}
		tank -= d;
		pos = A[i].a;
		Q.push(A[i].b);
	}
	printf("%d\n",ans);
}
int main()
{
	scanf("%d",&n);
	for(int i = 0;i < n;++i){
		scanf("%d%d",&A[i].a,&A[i].b);
	}
	scanf("%d%d",&L,&P);
	solve();
	return 0;
}

posted @ 2019-03-28 21:20  Zforw  阅读(32)  评论(0编辑  收藏  举报