[LeetCode] 787. Cheapest Flights Within K Stops K次转机内的最便宜航班
There are n
cities connected by m
flights. Each fight starts from city u
and arrives at v
with a price w
.
Now given all the cities and fights, together with starting city src
and the destination dst
, your task is to find the cheapest price from src
to dst
with up to k
stops. If there is no such route, output -1
.
Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph looks like this:
The cheapest price from city0
to city2
with at most 1 stop costs 200, as marked red in the picture.
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph looks like this:
The cheapest price from city0
to city2
with at most 0 stop costs 500, as marked blue in the picture.
Note:
- The number of nodes
n
will be in range[1, 100]
, with nodes labeled from0
ton
- 1
. - The size of
flights
will be in range[0, n * (n - 1) / 2]
. - The format of each flight will be
(src,
dst
, price)
. - The price of each flight will be in the range
[1, 10000]
. k
is in the range of[0, n - 1]
.- There will not be any duplicated flights or self cycles.
Java:
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
Map<Integer, Map<Integer, Integer>> prices = new HashMap<>();
for (int[] f : flights) {
if (!prices.containsKey(f[0])) prices.put(f[0], new HashMap<>());
prices.get(f[0]).put(f[1], f[2]);
}
Queue<int[]> pq = new PriorityQueue<>((a, b) -> (Integer.compare(a[0], b[0])));
pq.add(new int[] {0, src, k + 1});
while (!pq.isEmpty()) {
int[] top = pq.remove();
int price = top[0];
int city = top[1];
int stops = top[2];
if (city == dst) return price;
if (stops > 0) {
Map<Integer, Integer> adj = prices.getOrDefault(city, new HashMap<>());
for (int a : adj.keySet()) {
pq.add(new int[] {price + adj.get(a), a, stops - 1});
}
}
}
return -1;
}
}
Python:
class Solution(object):
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
adj = collections.defaultdict(list)
for u, v, w in flights:
adj[u].append((v, w))
best = collections.defaultdict(lambda: collections.defaultdict(lambda: float("inf")))
min_heap = [(0, src, K+1)]
while min_heap:
result, u, k = heapq.heappop(min_heap)
if k < 0 or best[u][k] < result:
continue
if u == dst:
return result
for v, w in adj[u]:
if result+w < best[v][k-1]:
best[v][k-1] = result+w
heapq.heappush(min_heap, (result+w, v, k-1))
return -1
Python:
class Solution(object):
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
f = collections.defaultdict(dict)
for a, b, p in flights:
f[a][b] = p
heap = [(0, src, k + 1)]
while heap:
p, i, k = heapq.heappop(heap)
if i == dst:
return p
if k > 0:
for j in f[i]:
heapq.heappush(heap, (p + f[i][j], j, k - 1))
return -1
C++:
// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|)
// Space: O(|E| + |V|) = O(|E|) class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
using P = pair<int, int>;
unordered_map<int, vector<P>> adj;
for (const auto& flight : flights) {
int u, v, w;
tie(u, v, w) = make_tuple(flight[0], flight[1], flight[2]);
adj[u].emplace_back(v, w);
} unordered_map<int, unordered_map<int, int>> best;
using T = tuple<int, int, int>;
priority_queue<T, vector<T>, greater<T>> min_heap;
min_heap.emplace(0, src, K + 1);
while (!min_heap.empty()) {
int result, u, k;
tie(result, u, k) = min_heap.top(); min_heap.pop();
if (k < 0 ||
(best.count(u) && best[u].count(k) && best[u][k] < result)) {
continue;
}
if (u == dst) {
return result;
}
for (const auto& kvp : adj[u]) {
int v, w;
tie(v, w) = kvp;
if (!best.count(v) ||
!best[v].count(k - 1) ||
result + w < best[v][k - 1]) {
best[v][k - 1] = result + w;
min_heap.emplace(result + w, v, k - 1);
}
}
}
return -1;
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 787. Cheapest Flights Within K Stops K次转机内的最便宜航班的更多相关文章
- LeetCode 787. Cheapest Flights Within K Stops
原题链接在这里:https://leetcode.com/problems/cheapest-flights-within-k-stops/ 题目: There are n cities connec ...
- [LeetCode] 787. Cheapest Flights Within K Stops_Medium tag: Dynamic Programming, BFS, Heap
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...
- 【LeetCode】787. Cheapest Flights Within K Stops 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:BFS 参考资料 日期 题目 ...
- [LeetCode] Cheapest Flights Within K Stops K次转机内的最便宜的航班
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...
- 787. Cheapest Flights Within K Stops
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...
- [Swift]LeetCode787. K 站中转内最便宜的航班 | Cheapest Flights Within K Stops
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...
- Java实现 LeetCode 787 K 站中转内最便宜的航班(两种DP)
787. K 站中转内最便宜的航班 有 n 个城市通过 m 个航班连接.每个航班都从城市 u 开始,以价格 w 抵达 v. 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是 ...
- LeetCode:二叉搜索树中第K小的数【230】
LeetCode:二叉搜索树中第K小的数[230] 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明:你可以假设 k 总是有效的,1 ≤ k ...
- LeetCode:乘法表中的第K小的数【668】
LeetCode:乘法表中的第K小的数[668] 题目描述 几乎每一个人都用 乘法表.但是你能在乘法表中快速找到第k小的数字吗? 给定高度m .宽度n 的一张 m * n的乘法表,以及正整数k,你需要 ...
随机推荐
- zookeeper题目
1. ZooKeeper是什么?2. ZooKeeper提供了什么?3. Zookeeper文件系统4. ZAB协议?5. 四种类型的数据节点 Znode6. Zookeeper Watcher 机制 ...
- test20190924 老L
80+50+100=230.T1没做出来说明我数列学得不好? LOLO 的含树 现有函数 \[ g_m(i)=\begin{cases} 0, & 0 \leq i \leq m\\ i-1+ ...
- B/S大附件上传,支持断点续传
核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. * 如何分片: * 如何合成一个文件: * 中断了从哪个分片开 ...
- am335x system upgrade kernel ethernet(四)
1 Scope of Document This document describes ethernet hardware design and porting KZS8081 to ubo ...
- WinDbg常用命令系列---清屏
.cls (Clear Screen) .cls命令清除调试器命令窗口显示. .cls 环境: 模式 用户模式下,内核模式 目标 实时. 崩溃转储 平台 全部 清屏前 清屏后
- 了解Python-白 驹 过 隙 , 忽 然 而 已
白 驹 过 隙 , 忽 然 而 已 人 生 苦 短,我 用 Python -- Life is short , you need Python 代码量少,同一样问题 ,用不同的语言解决时,一般情况下P ...
- QQ for Mac聊天纪录怎么查找??
在你Mac上打开你的QQ,选择任意聊天窗口,打字的上面有6个图表快捷键,第6个就是查看聊天记录的功能键
- hexo绑定个人域名
前段时间用 hexo 搭建的 gitpage 个人博客,服务器用的是 github 的,然后域名默认也是 github 下的二级域名:username.github.io, 现在为了提升格调准备将自己 ...
- 【cf补题记录】A. Hotelier
思考之后再看题解,是与别人灵魂之间的沟通与碰撞 A. Hotelier 题意 给出长度为n的字符串,字符串由'L'.'R'以及数字0~9组成.旅馆有10间房子,L代表客人从左边入住,R代表客人从右边入 ...
- 【转】Android ROM分析(1):刷机原理及方法
一.刷机原理 android系统启动的时候,首先会进行一些诸如硬件自检之类的操作,这些操作完成以后(至少它应该知道当前的机器有没有电),会检查一下当前手机按键的状态(接下来就是所谓刷机模式切换了,不同 ...