当前位置:网站首页>871. Minimum refueling times: simple priority queue (heap) greedy question
871. Minimum refueling times: simple priority queue (heap) greedy question
2022-07-02 14:51:00 【Gong Shui Sanye's Diary of writing questions】
Title Description
This is a LeetCode Upper 871. Minimum refueling times , The difficulty is difficult .
Tag : 「 greedy 」、「 Priority queue ( Pile up )」、「 simulation 」
The car set off from the starting point to the destination , The purpose is to the east of the starting position target Miles away .
There are gas stations along the way , Every station[i] For a gas station , It's east of the starting point station[i][0] Miles away , And there are station[i][1] A litre of petrol .
Suppose the capacity of the car's fuel tank is infinite , At first there was startFuel Liter fuel . Every time it drives Miles will be used A litre of petrol .
When the car arrives at the gas station , It may stop to refuel , Transfer all gasoline from the gas station to the car .
In order to reach the destination , What's the minimum number of refuels necessary for a car ? If you can't get to your destination , Then return to .
Be careful : If the remaining fuel when the car arrives at the gas station is , It can still refuel there . If the remaining fuel is , Still think it has reached its destination .
Example 1:
Input :target = 1, startFuel = 1, stations = []
Output :0
explain : We can get to our destination without refueling .
Example 2:
Input :target = 100, startFuel = 1, stations = [[10,100]]
Output :-1
explain : We can't get to our destination , Not even getting to the first gas station .
Example 3:
Input :target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output :2
explain :
We set out with 10 Liter fuel .
We drove to the starting point 10 The gas station at mile , Consume 10 Liter fuel . Take the gas from 0 To add to 60 l .
then , We from 10 The gas station is miles away 60 The gas station at mile ( Consume 50 Liter fuel ),
And take the gas from 10 To add to 50 l . Then we drove to our destination .
We are on the way 1 Two gas stations stop , So back 2 .
Tips :
greedy + Priority queue ( Pile up )
For convenience , We remember target by t, remember startFuel by start, remember stations by ss.
We can simulate the progress , Use n Represents the total number of gas stations ,idx Represents the subscript of the passing gas station , Use remain Represents how much oil there is currently ( Starting with remain = start),loc Represents how far we have gone ,ans For the answer ( At least the number of times you need to refuel ).
as long as loc < t, The representative hasn't arrived yet ( after ) Target location , We can continue to simulate the progress , Each time will be remain Add up to loc in , It means to use up the remaining oil , The farthest you can go , At the same time, the location ss[idx][0] <= loc The number of gas stations added to the priority queue ( Big root pile , Reverse the order according to the oil quantity ) in , Check again whether loc < t( Next cycle ), At this time, due to emptying the remaining oil remain, We try from the priority queue ( Big root pile ) Take out the gas station with the largest fuel volume in the past and refuel ( At the same time, the number of refueling ans Add one operation ), Use new remaining oil remain Repeat the process , Until you meet loc >= t Or no oil to add .
It is easy to prove the correctness of this practice : It also consumes one refueling time , Always choose the gas station with the largest fuel volume to refuel , It can ensure that there is no better result .
Code :
class Solution {
public int minRefuelStops(int t, int start, int[][] ss) {
PriorityQueue<Integer> q = new PriorityQueue<>((a,b)->b-a);
int n = ss.length, idx = 0;
int remain = start, loc = 0, ans = 0;
while (loc < t) {
if (remain == 0) {
if (!q.isEmpty() && ++ans >= 0) remain += q.poll();
else return -1;
}
loc += remain; remain = 0;
while (idx < n && ss[idx][0] <= loc) q.add(ss[idx++][1]);
}
return ans;
}
}
Time complexity : Spatial complexity :
Last
This is us. 「 Brush through LeetCode」 The first of the series No.871 piece , The series begins with 2021/01/01, As of the start date LeetCode I have in common 1916 questions , Part of it is a locked question , We will finish all the questions without lock first .
In this series , In addition to explaining the idea of solving problems , And give the most concise code possible . If the general solution is involved, there will be corresponding code templates .
In order to facilitate the students to debug and submit code on the computer , I've built a warehouse :https://github.com/SharingSource/LogicStack-LeetCode .
In the warehouse address , You can see the links to the series 、 The corresponding code of the series 、LeetCode Links to the original problem and other preferred solutions .
边栏推荐
- NLA natural language analysis realizes zero threshold of data analysis
- [development environment] StarUML tool (download software | StarUML installation | StarUML creation project)
- 3、函数指针和指针函数
- Fabric. Keep the original level when JS element is selected
- taobao. trade. memo. Add (add remarks to a transaction) interface, Taobao store flag insertion interface, Taobao order flag insertion API interface, oauth2.0 interface
- Slashgear shares 2021 life changing technology products, which are somewhat unexpected
- Onnx+tensorrt: write preprocessing operations to onnx and complete TRT deployment
- YoloV6训练:训练自己数据集遇到的各种问题
- taobao. trades. sold. Get query the transaction data that the seller has sold (according to the creation time), Taobao store sales order query API interface, Taobao R2 interface, Taobao oauth2.0 trans
- Fabric.js 自由绘制椭圆
猜你喜欢

蜻蜓低代码安全工具平台开发之路

Xilinx Vivado set *. svh as SystemVerilog Header

What is erdma? Popular science cartoon illustration

LeetCode 2310. 个位数字为 K 的整数之和

Edit the formula with MathType, and set it to include only mathjax syntax when copying and pasting

Error: NPM warn config global ` --global`, `--local` are deprecated Use `--location=global` instead.

Reuse and distribution

Li Chuang EDA learning notes 15: draw border or import border (DXF file)

【空间&单细胞组学】第1期:单细胞结合空间转录组研究PDAC肿瘤微环境

Pychart connects to the remote server
随机推荐
没有从远程服务器‘‘映射到本地用户‘(null)/sa‘的远程用户‘sa‘及服务主密码解密错误的解决办法
Xilinx Vivado set *.svh as SystemVerilog Header
3、函数指针和指针函数
Development and design of animation surrounding mall sales website based on php+mysql
Advanced C language (realize simple address book)
Socket and socket address
Borui data integrated intelligent observable platform was selected into the "Yunyuan production catalogue" of China Academy of communications in 2022
geoserver离线地图服务搭建和图层发布
kityformula-editor 配置字号和间距
Reuse and distribution
Understanding of mongodb
jmeter脚本参数化
4、数组指针和指针数组
删除元素(带过渡动画)
Available solution development oral arithmetic training machine / math treasure / children's oral arithmetic treasure / intelligent math treasure LCD LCD driver ic-vk1622 (lqfp64 package), original te
Wechat applet uses towxml to display formula
为什么只会编程的程序员无法成为优秀的开发者?
广州市应急管理局发布7月高温高湿化工安全提醒
##51单片机实验之简易验证码发生器
Tujia muniao meituan has a discount match in summer. Will it be fragrant if the threshold is low?