LeetCode 871. Minimum Number of Refueling Stops 最少加油次数

LeetCode 871. Minimum Number of Refueling Stops

本题是LeetCode 871题,最少加油次数。

题目描述

A car travels from a starting position to a destination which is target miles east of the starting position.

Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.

The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.

When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.

Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

有一辆车从起点向东开,要求到达target距离远的目的地,途中有若干加油站,并给出加油站距起点的距离以及油量。汽车到达某加油站可以选择停下加油,将加油站所有的油转到车上。每走1英里消耗1升油。油量为0就开不了了,开始时车上有一定量的油。这辆车到达目的地最少需要加油几次,如果无法到达就返回-1。

解析

本题要求加油次数尽可能的少,可以用贪心的方法解决,能不加就不加,非得加就加最多的(反正都算一次)。每遇到一个加油站如果油量充足,就把这个加油站的油量存下来,如果遇到油量不足以开到下一站(或终点)就从存下来的油量里找最大的加,从大到小,直到满足开到下一站,如果全加上都开不到,那就说明无法到达。
C++代码如下:

int minRefuelStops(int target, int startFuel, vector<vector<int>> & stations)
{
	//greedy
	if (startFuel >= target) return 0;
	else if (stations.empty()) return -1;
	int cur = startFuel;
	priority_queue<int> f;
	int next = 0;
	int cnt = 0;
	while (next < stations.size() && cur >= stations[next][0] || !f.empty()) {
		//if the car can reach the next station, no need to refuel, save the fuel in a priority queue
		while ((next < stations.size() && cur >= stations[next][0])) f.push(stations[next++][1]);
		cur += f.top();
		f.pop();
		++cnt;
		if (cur >= target) return cnt;
	}
	return -1;
}

首先如果初始油量大于目的地距离,无需加油一定可以到达,返回0即可;
反之如果初始油量不够但是又没有加油站,那一定到不了,返回-1即可。
其他情况,我们需要顺序遍历所有加油站,当然题目包含提示加油站信息是按照距离从近到远给出的,所以无需我们再排序了。
为了从大到小的保存油量信息,我们用到了优先队列。这里使用从大到小的优先队列(top最大)由于是模板默认,简略写了,写全的话应该是priority_queue<int,vector<int>,less<int>> f用于保存能够到达但是没有加油的那些加油站的油量,以备不时之需。
然后定义cur是当前油量,next是下一个加油站索引,初始为0
那么车什么时候能继续开呢,分两种情况,一是当前油量足以坚持到下一个加油站(当然要先验证next索引不越界),或者保存的油量f不为空(这样我们可以在对应的加油站先加好油)
这种情况下,如果属于能够开到下一站,那么就一直开,不加油,同时将油量放入优先队列。如果开不到下一站,就从优先队列从大到小(从top)依次取油,等于在对应的加油站加了一次油,加油次数要加一,同时优先队列弹出top元素。在过程中判断cur是否超过了target距离,超过了说明能够开到终点,后续都不用加油,返回当前的加油次数即可。
如果上述条件不满足了(跳出了外层while循环)说明无法到达下一站并且没油可加,那显然到不了终点了,返回-1.
注意这里并没有计算每经过一段距离油量的变化,因为题目给出的都是终点以及加油站距离起点的坐标,所以cur记录的是累积的油量,累积油量大于到起点的距离就证明可达。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值