poj2431 -- Expedition

题目地址:
http://poj.org/problem?id=2431

题目大意:
给n个城镇,分别是坐标和能加的油的数量,最后给车的位置l,和当前油的数量,每走一个单位,油会漏1点,问最后到达0至少需要加多少油,如果不能到达输出-1。

解题思路:
使用优先队列,利用反向思维,只要能到达的地方,就把当前城镇的油push到优先队列里面,然后只要队列不空,就不断的加队头的油,直到油的量大于等于距离l,就可以结束了,如果过程中队列为空了且油量小于距离,那么就无法达到。

知识点:

声明:
priority_queue <int ,vector ,greater > q;
头文件:
queue
greater是从小到大排序,如果不写默认的是从大到小排
比如输入6 4 5
如果这样写 priority_queue < int > q;
会输出 6 5 4
priority_queue <int ,vector< int > ,greater< int > > q;
输出4 5 6

基本操作:

q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
q.back();//返回q的末尾元素

AC代码:

#include <iostream>
#include <queue>
#include <algorithm>

using namespace std;

struct city
{
	int l, num;
};

struct city c[1000010];

bool cmp(struct city x, struct city y)
{
	return x.l > y.l;
}

int main()
{
	ios::sync_with_stdio(false);
	
	int n, l, num, ans = 0;
	priority_queue<int> q;
	
	cin >> n;
	
	for (int i=0; i<n; i++)
	{
		cin >> c[i].l >> c[i].num;
	}
	
	sort(c, c+n, cmp);
	
	cin >> l >> num;
	
	q.push(num);
	num = 0;
	
	int num1 = 0, t = 0;
	
	while (!q.empty())
	{
		num+=q.top();
		q.pop();
		num1++; 
		
		if (num >= l)
		{
			break;
		}
		
		while (num >= l-c[t].l && t < n)
		{
			q.push(c[t++].num);
		}
	}
	
	if (num >= l)
	{
		cout << num1-1 << endl; 
	} 
	else
	{
		cout << -1 << endl;
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值