首页 > 其他 > 详细

Dijkstra’s Shortest Path Algorithm / LeetCode 787. Cheapest Flights Within K Stops

时间:2019-09-14 10:09:48      阅读:89      评论:0      收藏:0      [点我收藏+]

Dijkstra’s Shortest Path Algorithm

技术分享图片

实现详见:https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-using-priority_queue-stl/

需要注意的是,priority_queue并无法更新内部的元素,因此我们更新dist的同时,直接把新的距离加入pq即可。pq里虽然有outdated的dist,但是由于距离过长,他们并不会更新dist。

//  If there is shorted path to v through u. 
if (dist[v] > dist[u] + weight) { 
    // Updating distance of v 
    dist[v] = dist[u] + weight; 
    pq.push(make_pair(dist[v], v)); 
} 

时间复杂度 O(ElogV)

 

787. Cheapest Flights Within K Stops

本题的实质是 Dijkstra’s Shortest Path Algorithm,只不过追加了一个约束条件step。

class Solution {
public:
    typedef tuple<int,int,int> ti; // (dist,u,step)
    
    struct edge{
        int end;
        int weight;
    };
    
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
        vector<vector<edge>> graph(n,vector<edge>());
        for (auto flight:flights){
            graph[flight[0]].push_back({flight[1],flight[2]});
        }
        priority_queue<ti,vector<ti>,greater<ti>> q;
        q.emplace(0,src,K+1);
        
        while (!q.empty()){
            auto [dist,u,step]=q.top(); q.pop();
            if (u==dst) return dist;
            if (step==0) continue;
            for (auto [v,w]:graph[u]){
                q.emplace(dist+w,v,step-1);
            }
        }
        return -1;
    }
};

 

Dijkstra’s Shortest Path Algorithm / LeetCode 787. Cheapest Flights Within K Stops

原文:https://www.cnblogs.com/hankunyan/p/11518287.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!