787. K 站中转内最便宜的航班

题目描述:有 n 个城市通过 m 个航班连接。每个航班都从城市 u 开始,以价格 w 抵达 v。
现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 src 到 dst 最多经过 k 站中转的最便宜的价格。 如果没有这样的路线,则输出 -1。
解题思路一:动态规划,只需要考虑从src出发的所有路线,经过最多K次中转到达目的地的最小价格。达到每个地方的最小价格是这一次不中转和从其他地方中转一次到达当前位置的价格中较小的那一个,代码如下:

class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
        dp = [[float('inf')] * n for _ in range(2)]
        dp[0][src] = 0
        dp[1][src] = 0
        for i in range(K+1):
            for s, d, p in flights:
                dp[i&1][d] = min(dp[i&1][d], dp[~i&1][s]+p)
        return dp[K&1][dst] if dp[K&1][dst] < float('inf') else -1
        

解题思路二:dijkstra,直接搜索从出发点到目的地的最短路径,用优先级队列保存依次到达的地点,每次都先考虑花费最下的点,如果中转次数大于K 或者当前路径的花费已经不是最下的了,就不考虑此条路径,当达到目的地时,直接返回花费,代码如下:

class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
        graph = collections.defaultdict(dict)
        for s, d, p in flights:
            graph[s][d] = p
        best = {}
        q = [(0, 0, src)] #cost, k, dst
        while(q):
            cost, k, place = heapq.heappop(q)
            if k > K+1 or cost > best.get((k, place), float('inf')): continue
            if place == dst: return cost
            for d, p in graph[place].items():
                newcost = p + cost
                if newcost < best.get((k+1, d), float('inf')):
                    best[(k+1, d)] = newcost
                    heapq.heappush(q, (newcost, k+1, d))
        return -1
            
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值