POJ 2431 Expedition

贪心,及优先队列或堆的使用。当路过一个城市或加油站时,不一定需要立刻加油,而可以将其保存在一个优先队列中。当没有油时,再取出优先队列的头加入等量的油,加油的先后是等价的。以加油站为分段点考虑,并将距离转化为距起点的距离。距离需要排序,输入并不保证有序,否则会wrong answer。

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
int n;
struct City
{
	int a, b;
}city[10010];
bool cmp(const City& x, const City& y)
{
	return x.a < y.a;
}
int l, p;
void solve()  //  use the priority queue
{
	int ans = 0, tank = p, pos = 0;
	priority_queue<int> q;
	for (int i = 0; i <= n; i++)
	{
		int d = city[i].a - pos;  //  distance to next city
		while (tank < d)  //  need to go to the gas station
		{
			if (q.empty())  //  no gas station to use
			{
				printf("-1\n");  //  cannot go to the final city
				return;
			}
			//  need to use the gas station
			tank += q.top();
			ans++;
			q.pop();
		}
		//  already get to the next city
		tank -= d;
		pos = city[i].a;
		q.push(city[i].b);
	}
	printf("%d\n", ans);
}
int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
		scanf("%d%d", &city[i].a, &city[i].b);
	scanf("%d%d", &l, &p);
	for (int i = 0; i < n; i++)
		city[i].a = l - city[i].a;
	city[n].a = l;
	city[n].b = 0;
	//  without sort will cause wrong answer.
	sort(city, city + n + 1, cmp);
	solve();
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值