Leetcode 871

Leetcode 871 Minimum numbers of Refueliing Stops

一辆汽车要从起点开到终点,途中有几个加油站可以加油,但是到每个加油站需要一定路程的油。问到达终点最少需要几次加油。

解答

优先队列

class Solution {
public:
    int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
        int len = stations.size();
        if(!stations.empty() && startFuel<stations[0][0]) return -1;
        priority_queue<int> q;
        int fuel = startFuel;
        int ans=0;
        cout<<"ok"<<endl;

        for(int i=0;i<stations.size();i++){
            q.push(stations[i][1]);
            while(i+1<stations.size() && fuel<stations[i+1][0] && !q.empty()){
                fuel+=q.top();q.pop();ans++;
            }
            if(i+1<stations.size() && fuel<stations[i+1][0]) return -1;
        }


        while(fuel<target && !q.empty()){
            fuel+=q.top();q.pop();
            ans++;
        }
        if(fuel<target) return -1;
        return ans;
    }
};
全部评论

相关推荐

牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务