【问题标题】:Prim's MST implementation with priority queue errorPrim\ 的 MST 实现与优先级队列错误
【发布时间】:2022-09-27 22:57:33
【问题描述】:

我的算法计算了点之间的正确距离,然后在下面的测试用例的嵌套 for 循环中将一些值更新为较小的值。

我怀疑我的嵌套 for 循环的实现有错误?

5
0 0
0 2
1 1
3 0
3 2

答案应该是 7.064495102(我得到 7.650281540)

def minimum_distance(x, y):
    result = 0.
    distance = {}
    for i in range(len(x)):
        j=i+1
        while j<len(x):
            distance[i, j] = calc_distance(x[i], y[i], x[j],y[j])
            # distance.append([i, j, calc_distance(x[i], y[i], x[j],y[j])])
            j+=1
            
    cost = []
    parent = []
    for k in range(len(x)):
        cost.append([float(\'inf\'), k])
        parent.append([None, k]) 
    
    # [cost, vertex]
    cost[0] = [0,0]
    parent[0] = [-1,0]

    pq = min_heap(cost)
    cost_pq = pq.heapify()
    
    while len(cost_pq) != 0:
        v, cost_pq = pq.extract_min(cost_pq)
        min_cost, min_current_node = v[0], v[1]
        result += min_cost
        for edge in distance:
            for vertex in cost_pq:
                # check if cost_pq contains vertex edge[1]
                if vertex[1] == edge[1]:
                    vertex_index = cost_pq.index(vertex)
                    if cost_pq[vertex_index][0] > distance[edge[0], edge[1]]:
                        cost_pq[vertex_index][0] = distance[edge[0], edge[1]]
                        parent[edge[1]][0] = edge[0]
                        pq.heapify() 
            
    return result
  • 这种实现过于复杂并且没有多大意义。例如,堆应该存储边,而parent 对中的第二个值从不使用

标签: python algorithm data-structures minimum-spanning-tree prims-algorithm


【解决方案1】:

为了说明评论,这应该是这样的:

from itertools import combinations
import heapq

def distance(x1, y1, x2, y2):
    return ((x1-x2)**2 + (y1-y2)**2)**0.5

def MST(xs, ys):
    n = len(xs)
    # heap of tuples (distance, node1, node2)
    q = [(distance(xs[i], ys[i], xs[j], ys[j]), i, j) 
         for i, j in combinations(range(n), 2)]
    heapq.heapify(q)
    # each node is its own parent in the beginning
    parents = list(range(n))
    # naive parent implementation - should include depth to balance for better performance
    def parent(i):
        while parents[i] != i:
            i = parents[i]
        return i

    total_distance = 0
    while q:
        d, i, j = heapq.heappop(q)
        parent1, parent2 = parent(i), parent(j)
        if parent1 != parent2:
            total_distance += d
            parents[parent1] = j
    return total_distance

MST([0, 0, 1, 3, 3], [0, 2, 1, 0, 2]) 返回 7.06449510224598

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多