您的位置:首页 > 其它

poj 2431 Expedition 贪心 + 优先队列

2012-08-10 00:42 281 查看
题目大意:

有n个加油站,每个加油站的加油的油量有限,距离终点都有一个距离。

一个卡车的油箱无限,没走一个单元要消耗一单元的油,问卡车到达终点的最少加多少次油。

解题思路:

贪心。。。。。卡车走得越远越好,要是不能到达终点,就选择经过的油站里面,加油量最多的加油,然后继续。

所以先按照加油站距离终点的距离,从大到小排列。

利用优先队列来存经过的加油站,根据加油站加油的油量多少排序。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;

const int maxn = 10010;
struct node
{
	int dist, fuel;
};
node position[maxn];

int n, L, P;

bool cmp(const node &a, const node &b)
{
	return a.dist > b.dist;
}

int main()
{
	
	while(scanf("%d", &n) != EOF)
	{
		priority_queue<int> heap;
		for(int i = 0; i < n; i++)
			scanf("%d %d", &position[i].dist, &position[i].fuel);
		sort(position, position + n, cmp);
		scanf("%d %d", &L, &P);
		int t = 0;
		heap.push(P);
		int index = 0;
		while(L > 0 && !heap.empty())
		{
			t++;
			int tmp = heap.top();
			heap.pop();
			L -= tmp;
			while(index < n && L <= position[index].dist)
				heap.push(position[index++].fuel);
		}
		printf("%d\n", L <= 0? t - 1: -1);
	}
	
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: