繁体   English   中英

原始MST算法优化

[英]Prim MST algorithm optimization

我正在实现最小生成树的Prim算法。 该算法正常工作。 但是如果我有一个具有10000个节点的图形,则会花费太多时间。 这是我如何在代码中存储图形的示例:

graph = {0: {1: 6, 5: 3}, 
1: {0: 6 , 6: 3 , 2: 9}, 
2: {1: 9, 7: 3 , 3: 5}}

这是我如何获得青春期的方法:

def adjacent(graph, u): # adjacencies of vertex u
    return graph[u].keys()

这是我计算两个节点之间边缘的权重的方法:

def w(u,v):
    L = cartesian_product[u].keys()
    if v in L:
        return cartesian_product[u].get(v)
    return 999999

这是我使用Prim算法计算最小生成树宽度的算法:

def prim(graph):
    total_mst_cost=0
    # put all nodes in a heap
    h=[(0,0)] 
    for i in range(1,n*k):
        heappush(h, (999999,i))
    while len(h)!=0 : #till there is a node left in the heap
        (key,u) = heappop(h)
        total_mst_cost += key
        # check hte adjacences of node-->
        adj = adjacent(graph,u)

        f = operator.itemgetter(1)
        ff = map(f, h)
        for v in adj:
            # update the labels:
            _ww = w(u,v)
            try: i = ff.index(v)
            except: continue
            if v==h[i][1] and _ww < h[i][0]:
                h[i]=(_ww, h[i][1])
        heapify(h)
            # for i in range(len(h)):
            #     if v==h[i][1] and _ww < h[i][0]:
            #         h[i]=(_ww, h[i][1])
            #         heapify(h)
    return total_mst_cost

想法1

堆的初始化:

for i in range(1,n*k):
    heappush(h, (999999,i))

是不必要的。 如果所有节点都可以访问,则只需删除这两行。

想法2

重量提取:

L = cartesian_product[u].keys()

似乎很慢。 我不太确定cartesian_product的类型是什么,但是如果它是字典,那么与u in cartesian_product包含u in cartesian_product测试相比,应该比提取键列表并搜索它们更快。

想法3

您在每次迭代后调用heapify。 我相信这是因为您希望能够调整堆队列中的权重。

另一种更快的替代方法记录在此处的Python文档中]( https://docs.python.org/2/library/heapq.html#priority-queue-implementation-notes )并通过将某些值标记为已删除来工作使用字典。

想法4

如果这不是出于教育原因,我建议您使用Networkx,这是一个具有图形算法的Python库。 在此库中,您可以将所有代码替换为对minimum_spanning_tree的函数调用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM