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

题目链接: 传送门

Expedition

Time Limit: 1000MS     Memory Limit: 65536K

题目描述

驾驶一辆卡车行驶L单位距离。最开始有P单位的汽油。卡车每开1单位距离消耗1单位的汽油。在途中一共有N个加油站。假设卡车的燃料箱容量无限大,问如果到达终点最少的加油次数。

思路

在卡车开往终点途中,只有在加油站才可以加油,换做认为“在到达加油站i时,就获得了一次在之后任何时候都可以加油的权利”

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
struct oil{
	int dis,fuel;
};
bool cmp(struct oil x,struct oil y)
{
	return x.dis <= y.dis;
}

int main()
{
	int N;
	
	while (scanf("%d",&N) != EOF)
	{
		struct oil stops[10005];
		priority_queue<int>pque;
		int L,P;
		
		for (int i = 0;i < N;i++)
		{
			scanf("%d%d",&stops[i].dis,&stops[i].fuel);
		}
		
		scanf("%d%d",&L,&P);
		
		for (int i = 0;i < N;i++)
		{
			stops[i].dis = L - stops[i].dis;
		}
		
		sort(stops,stops + N,cmp);
		
		int cnt = 0;
		bool flag = true;
		for (int i = 0;i < N;i++)
		{
			if (P >= L)
			{
				break;
			}
			
			if (P < stops[i].dis)
			{
				if (pque.empty())
				{
					flag = false;
					break;
				}
				else
				{
					while (!pque.empty() && P < stops[i].dis)
					{
						cnt++;
						int tmp = pque.top();
						pque.pop();
						P += tmp;
					}
					if (pque.empty() &&  P < stops[i].dis)
					{
						flag = false;
						break;
					}
					pque.push(stops[i].fuel);
				}
			}
			else
			{
				pque.push(stops[i].fuel);
			}
		}
		
		if (P < L && !pque.empty())
		{
			int tmp = pque.top();
			pque.pop();
			P += tmp;
			cnt++;
		}
		
		if (!flag)
		{
			printf("-1\n");
		}
		else
		{
			printf("%d\n",cnt);
		}
	}
	return 0;
}
posted @   zxzhang  阅读(448)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航