[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,你需要 ...
随机推荐
- steam相关插件
批量激活key:https://greasyfork.org/zh-CN/scripts/32718-steamredeemkeys 批量卖卡:https://github.com/Nuklon/St ...
- 《团队作业第三、四周》五阿哥小组Scrum 冲刺阶段---Day2
<团队作业第三.四周>五阿哥小组Scrum 冲刺阶段---Day2 一.项目燃尽图 二.项目进展 20182310周烔今日进展: 主要任务一览:完成总博客的提交,制定接下来的计划,编写博客 ...
- Java LinkedList add vs push
Java LinkedList add 是加在list尾部. LinkedList push 施加在list头部. 等同于addFirst.
- jedis的连接池
1.需要先打开虚拟机,并开启Linux系统的端口号:6379: 其中,第一行代码为修改字符编码格式,解决SSH中文乱码问题. 2.开启redis: 3.利用连接池实现数据的存取: (1)代码实现: i ...
- Log4net 数据库存储(四)
1.新建一个空的ASP.Net 空项目,然后添加Default.aspx窗体 2.添加配置文件:log4net.config <?xml version="1.0" enco ...
- Cogs 727. [网络流24题] 太空飞行计划(最大权闭合子图)
[网络流24题] 太空飞行计划 ★★☆ 输入文件:shuttle.in 输出文件:shuttle.out 简单对比 时间限制:1 s 内存限制:128 MB [问题描述] W 教授正在为国家航天中心计 ...
- P4218 [CTSC2010]珠宝商
P4218 [CTSC2010]珠宝商 神题... 可以想到点分治,细节不写了... (学了个新姿势,sam可以在前面加字符 但是一次点分治只能做到\(O(m)\),考虑\(\sqrt n\)点分治, ...
- 洛谷 P1821 [USACO07FEB]银牛派对Silver Cow Party 题解
P1821 [USACO07FEB]银牛派对Silver Cow Party 题目描述 One cow from each of N farms (1 ≤ N ≤ 1000) conveniently ...
- CSS3之碰撞反弹动画无限运动
示例代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...
- springboot2.0整合redis作为缓存以json格式存储对象
步骤1 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spr ...