码迷,mamicode.com
首页 > 其他好文 > 详细

871 最低加油次数

时间:2019-01-26 00:49:14      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:循环   次数   code   vector   逻辑   push   back   ati   int start   

class Solution {
public:
    //startFuel的含义是我们的车能开的距离,如果startFuel > target,那么一次加油也不需要直接开到重点
    int minRefuelStops(int target, int startFuel, vector<vector<int>> &stations) {
        priority_queue<int> queue;
        int pos = 0, ans = 0;
        stations.push_back({target, 0});//我这里把终点加进去方便程序比较
        while (startFuel < target) {    //当油量不能撑到终点时循环
            while (pos < stations.size() - 1 && startFuel >= stations[pos][0])//把车当前油量所能开到的每一个加油站的油量都记下来
                queue.push(stations[pos++][1]);
            while (startFuel < stations[pos][0]) {//遇到下一站开不到则加油,使用priority_queue确保加的油量是经过的加油站里面最多的,把终点加进stations使得这一步逻辑就很方便
                if (queue.empty())                //把经过的所有加油站的油都加上都到不了,那就肯定到不了
                    return -1;
                startFuel += queue.top();         //加油
                queue.pop();
                ++ans;
            }
        }
        return ans;
    }
};

871 最低加油次数

标签:循环   次数   code   vector   逻辑   push   back   ati   int start   

原文地址:https://www.cnblogs.com/INnoVationv2/p/10322369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!