【Leetcode每日一题】787. K 站中转内最便宜的航班

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



题目

有 n 个城市通过一些航班连接。给你一个数组 flights ,其中 flights[i] = [from(i), to(i), price(i)] ,表示该航班都从城市 fromi 开始,以价格 price(i) 抵达 to(i)。

现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到出一条最多经过 k 站中转的路线,使得从 src 到 dst 的 价格最便宜 ,并返回该价格。 如果不存在这样的路线,则输出 -1。

示例

示例1

输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
输出: 200
解释: 从城市 0 到城市 2 在 1 站中转以内的最便宜价格是 200

示例2

输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
输出: 500
解释: 从城市 0 到城市 2 在 0 站中转以内的最便宜价格是 500


关键思路

题目本质为求最短路径,基本思路为维护一个方便查询最小价格的动态规划表。

代码实现

class Solution(object):
    def findCheapestPrice(self, n, flights, src, dst, k):
        """
        :type n: int  number of cities
        :type flights: List[List[int]]
        :type src: int
        :type dst: int
        :type k: int  max sites
        :rtype: int  min price or -1
        """

        cur = src
        open_list = [ [float("inf"), -1 ] for i in range(n)]
        open_list[0][0] = 0

        while cur!=dst:
            for flight in flights:
                if cur == flight[0]:  # match
                    if open_list[cur][0]+flight[2] <= open_list[flight[1]][0]:  # compare
                        if flight[1] <= dst and open_list[flight[1]][1] < k: # compare the number
                            open_list[flight[1]][0] = open_list[cur][0]+flight[2]  # update
                            open_list[flight[1]][1] += 1
            cur = cur+1
        
        return open_list[dst][0] if open_list[dst][0] != float("inf") else -1
    

if __name__ == "__main__":
    n = input()
    edges = input()
    src = input()
    dst = input()
    k = input()
    obj = Solution()
    result = obj.findCheapestPrice(n, edges, src, dst, k)
    print(result)

运行结果

200
500

链接

https://leetcode-cn.com/problems/cheapest-flights-within-k-stops

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值