POJ——2431题 Expedition

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/88114057

Expedition

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 25425   Accepted: 7070

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

使用优先队列解题,思路是来自算法挑战这本书,思路是将车每开到一个加油站就判断是否能开到下一个加油站,如不能则在之前的加油站中找油量最多的加上直至能到达下一个加油站。换个角度看确实很简单

需要注意的是——必须将加油站按照从近到远排序,否则答案会出错,另外也不要使用冒泡排序,那样会超时,最好使用stl中的sort排序

ac代码:

#include<iostream>
#include<algorithm>
#include<queue> 
#include<stdio.h>
using namespace std;
int l,p,n;
priority_queue<int> que;//创建一个最优队列,默认情况下最优队列会将队列中最大的数置于队顶 
int ans=0,pos=0,tank;//ans代表加油次数,pos代表此时所在位置,tank代表此时油箱中油的剩余量
struct input{//N+1行的数据
    int a;
    int b;
};
bool cmp(input a, input b)
{
    return a.a < b.a;
}
input date[1000001];
int main()
{
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>date[i].a>>date[i].b;
	} 
	cin>>l>>p; 
	tank=p; 
	date[n].a=0;date[n].b=0;//将终点也是算是一个加油站 
	n++;
	for(int i=0;i<n;i++){//将ai代表的到终点的距离修改为到起点的距离 
		date[i].a=l-date[i].a;
	} 
	sort(date,date+n,cmp);
	for(int i=0;i<n;i++){
        //去下一个加油站至少要前进的距离
		int d=date[i].a-pos;
		while(tank-d<0){//不断加油直到足够行驶到 下一个加油站 
			if(que.empty()){
				puts("-1");
				return 0;
			}
			tank+=que.top();
			que.pop();
			ans++;
		} 
		tank-=d;
		pos=date[i].a;
		que.push(date[i].b);
	}
	cout<<ans<<endl;
	return 0; 
}

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/88114057