leetcode.K站中转(python)

开始准备用dfs深度搜索,发现n=100,dfs可能会超时,即使用了剪枝。

python 复制代码
class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        length = k + 2
        ans = float('inf')
        rec = []
        vis = [True]*n
        edge = defaultdict(list)
        for f, t, p in flights:
            edge[f].append([t, p])

        def dfs(node, spend):
            nonlocal ans
            rec.append(node)
            vis[node] = False
            if node == dst:
                ans = min(ans, spend)
            elif len(rec) < length:
                for nex, p in edge[node]:
                    if not vis[nex]: continue
                    dfs(nex, spend + p)
            rec.pop()
            vis[node] = True
        dfs(src, 0)
        return ans if ans != float('inf') else -1

理所当然的想用bfs,n=100肯定不会超时,谁知道题目针对,这次内存超了。因为题目中

  • 0 <= flights.length <= (n * (n - 1) / 2)

相当于100*99/2,大概5000条路线呗。这就超了???

python 复制代码
class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        edge = defaultdict(dict)
        for f, t, p in flights:
            edge[f][t] = p
        qu = deque()
        ans = float('inf')
        qu.append([src, 0, -1])
        while qu:
            node, spend, num = qu.popleft()
            if num > k:continue
            if node == dst:
                ans = min( ans, spend )
                continue
            for nex in edge[node]:
                qu.append([nex, spend + edge[node][nex], num + 1])
        return ans if ans != float('inf') else -1

看见大佬的优化过程,叹为观止。

使用最小堆,每次弹出列表中最小花费的路径,利用steps避免走成一个环。发现我之前的问题,应该就是走进一个环中,导致数据增多,内存超了。

python 复制代码
import heapq as pq
class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        edge = defaultdict(dict)
        for f, t, p in flights:
            edge[f][t] = p
        qu = [[0, src, -1]]
        pq.heapify(qu)
        steps = [k+1]*n
        while qu:
            spend, node, num = pq.heappop(qu)
            if steps[node] <= num:continue
            steps[node] = num
            if node == dst:
                return spend
            for nex in edge[node]:
                pq.heappush(qu, [spend + edge[node][nex], nex, num + 1])
        return -1

下面是官方题解,使用dp。

使用dp动态规划算法,设dp【t】【i】,表示转到第t站,从src到达i所需的最小花费数;

那么dp【t】【i】 = min(dp【t】【i】,dp【t-1】【j】+cost【j】【i】),遍历所有路线。

python 复制代码
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(k+2)]
        dp[0][src] = 0
        ans = float('inf')
        for t in range(1, k+2):
            for j, i, p in flights:
                dp[t][i] = min(dp[t][i], dp[t-1][j] + p)
                if i == dst: ans = min (ans, dp[t][i])
        return ans if ans != float('inf') else -1

这个动态规划,内核也就是bfs。第一次只更新了从src出发到达的节点。这个方法稍稍不如bfs,因为每一步都走了一些不能走的点。

相关推荐
在世修行6 小时前
智学文枢:页面切换与跨页数据预填
python·桌面应用·signal·1024程序员节·pyside·跨页跳转·状态预填
2601_962885727 小时前
如何用 Python 把 K 线重采样成任意周期?
开发语言·python
打工仔折腾 AI7 小时前
在 Ubuntu ARM64 部署 Q1 V3.0 MuJoCo 模型:加载、单步推理与执行器响应解析
linux·运维·人工智能·python·深度学习·ubuntu·性能优化
信誓旦旦的程序猿8 小时前
【Python量化实战宝典 #21】北向资金跟随手册:聪明钱择时信号(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
严谨的麻辣烫8 小时前
静态 ISP 代理请求超时怎么排查?Python 与 curl 实战
python·http·requests·1024程序员节·网络排障
KeepRobots9 小时前
11-01 温哥华不回拨:用 60 行 Python 查你的工单系统会不会差一小时(KeepRobots 工程笔记)
python
xiao77mwq9 小时前
你以为 OCR 慢?实测 81.3 s 里全是故障代价:如何把「定格态」消掉,让耗时从 6.5 s 到 13 倍差距显出原形
python
深圳市益普科技有限公司10 小时前
半导体良率管理YMS:良率与设备参数的相关性,先拉哪几组数据
人工智能·python·算法
“AI国潮设计-小江”10 小时前
【AIGC实战】Python+SDXL打造“潮汕英歌舞IP”万能立牌插件,批量生成“发财元宝蛋糕”视觉营销方案(附源码)
开发语言·人工智能·python·prompt·aigc
砚底藏山河11 小时前
python量化实操:冷热分层存储
java·开发语言·python·金融