Graph Theory (5) ------ Minimum Spanning Tree

Source: Internet
Author: User

The Minimum Spanning Tree of an undirected graph G is a tree composed of the edges of all vertices connected to g in the graph, and its total weight is the lowest. The Minimum Spanning Tree exists when and only when G is connected.

If an edge e that does not belong to T is added to a tree T in any lifetime, a circle is generated. If any edge is removed from the circle, the features of the tree are restored. If the weight of edge e is lower than the value of the removed edge, the value of the newly generated tree is lower than that of the native tree. If the edges added each time during the tree T creation process avoid the smallest median of the edges in the circle, the value of the generated tree cannot be improved. The greedy algorithm for the Minimum Spanning Tree is established.

Algorithm Policy

An edge of the Minimum Spanning Tree is formed in each step. The algorithm maintains a set of edges A, keeping the following cycle unchanged:

Before each iteration, A is a subset of a minimum spanning tree.

In each step of the algorithm, determine an edge (u, v) so that after it is added to a, it still does not violate this cycle, that is, a and {(u, v )} is still a subset of a minimum spanning tree. This is called a safe side.

Based on the method for determining the Security edge, there are two Minimum Spanning Tree algorithms:

Prim algorithm

Make the minimal spanning tree grow step by step. Each step regards a node as the root and adds the edge to the top. At any time of the algorithm, you can see a vertex set that has been added to the tree. In each phase, select an edge (u, v) so that the weight of this edge is the smallest of the values of all u in the tree but V in the tree. Reserve the DV and PV values for each vertex. DV is the right to connect vertex V to the shortest edge of the vertex set added to the tree. PV is the final vertex that causes DV change. It can be seen that the prim algorithm is basically the same as the Dijkstra algorithm, but the DV definition is different. In the Dijkstra algorithm, DV is the shortest edge from V to the Source Vertex.

An Internet broadcast example:

Add all vertices to queue Q:

Select "A" as the source point and "A" as the output queue Q ", add it to the tree T, and update the" D "values of" B and "C:

The smallest edge is (a, B). Remove B from Q, add it to tree T, and update the D value of CDE.

The result is as follows:

Code:

Def prim (G, S): path ={} pre ={} alist = [] for V in G: alist. append (v) path [v] = sys. maxsize pre [v] = s path [s] = 0 queue = priorityqueue (PATH) queue. buildheap (alist) while queue. size> 0: vertex = queue. delmin () for V in vertex. getneighbors (): newpath = vertex. getweight (v) If V in queue. queue and newpath <path [v]: path [v] = newpath pre [v] = vertex queue. perup (v) newpath = vertex. getweight (v) return preif _ name __= = '_ main _': g = graph () g. addedge ('A', 'B', 2) g. addedge ('B', 'A', 2) g. addedge ('A', 'C', 3) g. addedge ('C', 'A', 3) g. addedge ('B', 'C', 1) g. addedge ('C', 'B', 1) g. addedge ('B', 'D', 1) g. addedge ('D', 'B', 1) g. addedge ('D', 'E', 1) g. addedge ('E', 'D', 1) g. addedge ('B', 'E', 4) g. addedge ('E', 'B', 4) g. addedge ('C', 'F', 5) g. addedge ('F', 'C', 5) g. addedge ('E', 'F', 1) g. addedge ('F', 'E', 1) g. addedge ('F', 'G', 1) g. addedge ('G', 'F', 1) U = G. getvertex ('A') Path = prim (G, u) for V in path: Print v. ID, 'after', path [v]. id output: A after AB after AC after BD after be after DF after eg After F

The prim algorithm runs on an undirected graph. Remember to add each edge to two adjacent tables. The runtime when the heap is not used is O (| v | 2), and the runtime when the binary heap is used is O (| E | log | v | ).

Kruskal Algorithm

Continuously selects an edge based on the minimum weight, and uses it as the selected edge when the selected edge does not generate a circle. In the form, the Kruskal algorithm processes a forest-a set of trees. This algorithm finds all edges connected to any two trees in the forest, and edges with the minimum weight are used as security edges. | V | A Single-node tree exists at the beginning. When an edge is added, the two trees are merged into a tree. When the algorithm is terminated, there is only one tree left. This tree is the minimum spanning tree. This algorithm uses the Union/find algorithm of the non-Intersection Set to determine the Security edge. For an edge (u, v), if u and v are in the same set, you must discard this edge because they are connected, and then add this edge to form a circle.

When selecting an edge, you can sort the Edge Based on the Edge Weight and select the edge from small to large. However, it is better to build a heap.

class Vertex(object):    def __init__(self,key):        self.id=key        self.adj={}        self.parent=None        self.rank=0    def addNeighbor(self,nbr,weight=0):        self.adj[nbr]=weight    def getNeighbors(self):        return self.adj.keys()    def getId(self):        return self.id    def getWeight(self,key):        return self.adj[key]def Kruskal(G):    elist=[]    accpeted_e_list=[]    for v in G:        for vertex in v.getNeighbors():            e=Edge(v,vertex,v.getWeight(vertex))            elist.append(e)    queue=KruskalQueue(elist)    queue.buildHeap()    edge_num=0    while edge_num<G.size-1:        e=queue.delMin()        u=e.u        v=e.v        uset=Find(u)        vset=Find(v)        if uset!=vset:            accpeted_e_list.append(e)            edge_num+=1            Union(uset,vset)    return accpeted_e_list      class Edge(object):    def __init__(self,u,v,weight):        self.u=u        self.v=v        self.weight=weightclass KruskalQueue(object):    def __init__(self,elist):        self.elist=elist        self.size=len(self.elist)    def buildHeap(self):        for i in xrange(self.size/2-1,-1,-1):            self.perDown(i)    def delMin(self):        self.elist[0],self.elist[-1]=self.elist[-1],self.elist[0]        e=self.elist.pop()        self.size-=1        self.perDown(0)        return e    def perDown(self,i):        left=2*i+1        right=2*i+2        little=i        if left<=self.size-1 and self.elist[i].weight>self.elist[left].weight:            little=left        if right<=self.size-1 and self.elist[little].weight>self.elist[right].weight:            little=right        if little!=i:            self.elist[i],self.elist[little]=self.elist[little],self.elist[i]            self.perDown(little)    def perUp(self,i):        if i>0 and self.elist[i].weight<self.elist[(i-1)/2].weight:            self.elist[i],self.elist[(i-1)/2]=self.elist[(i-1)/2],self.elist[i]            self.perUp((i-1)/2)        def Find(v):    if v.parent is None:        return v    else:        v.parent=Find(v.parent)        return v.parentdef Union(u,v):    if u.rank<=v.rank:        u.parent=v        if u.rank==v.rank:            v.rank+=1    else:        v.parent=u    if __name__==‘__main__‘:    g= Graph()    g.addEdge(‘a‘,‘b‘,2)    g.addEdge(‘a‘,‘c‘,3)    g.addEdge(‘b‘,‘c‘,1)    g.addEdge(‘b‘,‘d‘,1)    g.addEdge(‘d‘,‘e‘,1)    g.addEdge(‘b‘,‘e‘,4)    g.addEdge(‘f‘,‘c‘,5)    g.addEdge(‘f‘,‘e‘,1)    g.addEdge(‘g‘,‘f‘,1)    elist=Kruskal(g)    for e in elist:        print ‘edge(%s,%s)‘%(e.u.id,e.v.id)

Output:

>>> edge(b,c)edge(f,e)edge(b,d)edge(g,f)edge(d,e)edge(a,b)

The worst case of an algorithm is O (| E | log | E |), which is controlled by heap operations. E = O (V2) when the figure is dense, and the actual running time is O (elogv ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.