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

Posted hankunyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    
;

 

以上是关于Dijkstra’s Shortest Path Algorithm / LeetCode 787. Cheapest Flights Within K Stops的主要内容,如果未能解决你的问题,请参考以下文章

HDU4725 The Shortest Path in Nya Graph(堆优化的dijkstra算法)

JAVA之单源最短路径(Single Source Shortest Path,SSSP问题)dijkstra算法求解

AtCoderD - Shortest Path Queries 2 dp

HDU 4725 The Shortest Path in Nya Graph(构图)

ecnu 1817 Shortest path

Dijkstra Shortest-Paths 快速重新计算,如果只有一条边被移除