POJ 2431 Expedition (贪心、优先队列)

题目链接:http://poj.org/problem?id=2431


题意:起点到终点之间有n个加油站,输入第一行为n,后面n行每行是该加油站距终点的距离和能加多少油。1单位油能开1单位距离。最后一行是起点到终点的距离和初始油箱里有多少油。问最少加几次油能到终点,不能到的话输出-1 。


先将所有的加油站按距离起点的距离从小到大排序,然后模拟车开的过程,每经过一个加油站只要油箱里还有油就不加油,将所有经过的加油站的加油数量存到一个大顶堆里,然后每当油箱没油了就从前面的加油站里选一个能加最多油的加上,也就是取大顶堆的顶。这样一直到终点。若任何一次油箱没油了也加不上油那就输出-1。


————挑战程序设计竞赛


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
int L, P; //L为起点距终点的距离,P为起始有多少油 
struct node{
	int dis, oil; //dis为加油站距离起点的距离 ,oil为能加多少油 
};
node sta[10010];
bool cmp(node a, node b) {
	return a.dis < b.dis;
}
int main() {
	int n;
	while(~scanf("%d", &n)) {
		int i, j;
		for(i = 0; i < n; i++) {
			scanf("%d %d", &sta[i].dis, &sta[i].oil);
		}
		scanf("%d %d", &L, &P);
		for(i = 0; i < n; i++) {
			sta[i].dis = L - sta[i].dis; //输入的是加油站距离终点的距离,要转换成距离起点 
		}
		sort(sta, sta + n, cmp);  //按照距离起点距离升序排序 
		int ans = 0, pos = 0; //ans加多少次油, pos当前位置 
		priority_queue<int> q;
		sta[n].dis = L; //将终点添加到加油站末尾,方便计算 
		sta[n].oil = 0; //终点不能加油 
		for(i = 0; i <= n; i++) {
			int tmp = sta[i].dis - pos;  //当前位置距下一个加油站的距离 
			while(tmp > P) { //不能开这么远的话要加油 
				if(q.empty()) {
					printf("-1\n");
					return 0;
				}
				else {
					P += q.top();
					q.pop();
					ans++;
				}
			}
			P -= tmp;
			pos = sta[i].dis; 
			q.push(sta[i].oil);
		}
		printf("%d\n", ans);
	} 
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值