minimum spanning tree

首先我们要给出下面一个概念,如何可以节约空间地保存无向图:


    a = [100 for i in range(int(10*11/2))]
    def update(i,j,l):
        if i > j:
            a[int(i*(i+1)/2+j)] = l
        else:
            a[int(j*(j+1)/2+i)] = l
    def length(i,j):
        if i > j:
            return a[int(i*(i+1)/2+j)]
        else:
            return a[int(j*(j+1)/2+i)]
    update(1,0,2)
    update(2,0,8)
    update(3,1,4)
    update(4,2,7)
    update(5,3,12)
    update(5,4,11)
    update(6,0,1)
    update(6,1,3)
    update(6,2,9)
    update(6,3,5)
    update(6,4,6)
    update(6,5,10)


基于python的简单实现:

def prime(start):
    list_a = [0,1,2,3,4,5,6]
    list_s = [start]
    dist = 0
    
    while True:
        if len(list_s) == 7:
            return dist
        temp = {}
        for i in list_s:
            for j in list(set(list_a)-set(list_s)):
                if length(i,j) < 100:
                    temp[length(i,j)] = [i,j]
        dist += min(temp)
        list_s.append(temp[min(temp)][1])
                

以上prime算法基于点,所以比较适合稠密图。

接下来介绍一个更适合稀疏图的算法,基于边:


Python的代码实现如下:

def kruskal():
    list_s = []
    path = []
    dist = 0
    E = {}
    for i in range(0,7):
        for j in range(0,i):
            E[(i,j)] = length(i,j)
    while (len(list_s) < 7 ):
        i1 = min(E.items(), key=lambda E: E[1])[0][0]
        j1 = min(E.items(), key=lambda E: E[1])[0][1]
        min_path = min(E.items(), key=lambda E: E[1])[0]
        min_dist = min(E.items(), key=lambda E: E[1])[1]
        E.pop(min_path)
        if i1 in list_s and j1 in list_s:
            pass
        else:
            path.append(min_path)
            dist += min_dist
            if i1 in list_s:
                list_s.append(j1)
            else:
                list_s.append(i1)
                if j1 in list_s:
                    pass
                else:
                    list_s.append(j1)
    return [dist,path]
            

if __name__ == '__main__':
    a = [100 for i in range(int(7*8/2))]
    def update(i,j,l):
        if i > j:
            a[int(i*(i+1)/2+j)] = l
        else:
            a[int(j*(j+1)/2+i)] = l
    def length(i,j):
        if i > j:
            return a[int(i*(i+1)/2+j)]
        else:
            return a[int(j*(j+1)/2+i)]
    
    update(1,0,2)
    update(2,0,8)
    update(3,1,4)
    update(4,2,7)
    update(5,3,12)
    update(5,4,11)
    update(6,0,1)
    update(6,1,3)
    update(6,2,9)
    update(6,3,5)
    update(6,4,6)
    update(6,5,10)

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页