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

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;
    }
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/11518287.html