Prim 是按什么顺序加边的

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

看 Prim 从 0 出发时,四条边是按什么顺序加进来的:

import heapq

def prim(edges, verts, s):
    ad = {u: [] for u in verts}
    for a, b, w in edges:
        ad[a].append((w, b))
        ad[b].append((w, a))
    seen = {s}
    pq = [(w, s, v) for w, v in ad[s]]
    heapq.heapify(pq)
    total = 0
    picked = []
    while pq and len(seen) < len(verts):
        w, u, v = heapq.heappop(pq)
        if v in seen:
            continue
        seen.add(v)
        total += w
        picked.append((u, v))
        for w2, x in ad[v]:
            if x not in seen:
                heapq.heappush(pq, (w2, v, x))
    return total, picked

t, p = prim([(0, 1, 2), (0, 2, 1), (1, 3, 3), (2, 4, 9), (3, 4, 1)], [0, 1, 2, 3, 4], 0)
print("/".join("%d-%d" % (a, b) for a, b in p))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论