Minimum spanning tree-prim algorithm and Kruskal algorithm

Source: Internet
Author: User

Reprinted from: http://www.cnblogs.com/biyeymyhjob/archive/2012/07/30/2615542.html minimum spanning tree-prim algorithm and Kruskal algorithm

Prim algorithm

1. Overview

Primm algorithm (prim algorithm), an algorithm in graph theory, can search for the smallest spanning tree in weighted connected graphs. This means that the subset of edges searched by this algorithm includes not only all the vertices in the connected graph ( English :Vertex (graph theory)), but also the sum of the weights of all the edges is minimal. The algorithm was discovered in 1930 by the Czech mathematician Voytech Jarnik ( English :vojtěch Jarník), and in 1957 by the American computer scientist Robert Prim ( english :Robert c. Prim) independent discovery; In 1959, Aizeg Dicos found the algorithm again. Therefore, in some cases, the Primm algorithm is also known as the DJP algorithm, the Delphi algorithm, or the Primm-Rockwell algorithm.

2. Simple description of the algorithm

1). Input: A weighted connected graph, where the vertex set is V and the edge set is E;

2). Initialize: Vnew = {x}, where x is any node in the Set V (Start point), enew = {}, is empty;

3). Repeat the following operations until Vnew = V:

A. Select the edge <u with the least weight in set E, V>, where U is the element in the collection vnew, and V is not in the Vnew collection, and v∈v (if there are several edges that satisfy the foregoing conditions, one of them can be arbitrarily selected);

B. Add v to the Set vnew, add <u, v> side to the set enew;

4). Output: Use the collection vnew and enew to describe the resulting minimum spanning tree.

The following is a description of the algorithm's legend

legend Description not selectable options available selected (vnew)

This is the original weighted connected graph. The number on each side of the edge represents its weight value. - - -

Vertex D is arbitrarily selected as the starting point. Vertices A,B,E , and F are connected to D through A single edge. a is the closest vertex of the distance D , so a and the corresponding side AD are highlighted. C, G A, B, E, F D

The next vertex is the nearest vertex from D or a . B distance D is 9, distance A is 7,E is a,F is 6. Therefore,F is nearest to D or A , so the vertex F is highlighted with the corresponding edge DF . C, G B, E, F A, D
The algorithm continues to repeat the above steps. Vertex B with distance a of 7 is highlighted. C B, E, G A, D, F

In the current case, you can choose between C,E and G . C distance b is 8,E is 7, andG is from F 11. e is recently highlighted as Vertex e with the corresponding edge be. No C, E, G A, D, F, B

Here, the vertices available for selection are only C and G. c is 5,G is 9, so Cis selected and highlighted with the side EC . No C, G A, D, F, B, E

Vertex G is the only remaining vertex, which is 11 from F , 9 from e , ande is recently highlighted as G and the corresponding edge EG. No G A, D, F, B, E, C

All vertices are now selected, and the green part of the graph is the smallest spanning tree of the connected graph. In this example, the sum of the weights of the minimum spanning tree is 39. No No A, D, F, B, E, C, G

3. Simple Proof Prim algorithm

Disprove: Suppose prim generates not the smallest spanning tree

1). Set prim to generate a tree of G0

2). Assume that the presence of Gmin makes the cost (Gmin) <cost (G0) exist in Gmin <u,v> does not belong to G0

3). Add <u,v> join G0 to get a ring, and <u,v> is not the longest edge of the ring (this is because <u,v>∈gmin)

4). This contradicts the shortest edge of prim each generation

5). Therefore, the hypothesis is not established, the proposition is proved.

4. Algorithm code implementation (not verified)

#define MAX  100000#define vnum  10+1                                             //There is no point with id 0, so ID number range 1~10int edge[vnum][vnum]={/* input adjacency matrix */};int LOWCOST[VNUM]={0};                                         Record V
New
The shortest side int addvnew[vnum] of the adjacency point in each point in the V;                                             Mark whether a point joins V
New
int adjecent[vnum]={0};                                        Record V vs. v
New
Nearest point void Prim (int start) {     int sumweight=0;     int i,j,k=0;     for (i=1;i<vnum;i++)                                      //vertex is starting from 1     {        lowcost[i]=edge[start][i];        Addvnew[i]=-1;                                         Put all points as V
New
, within V, as long as the corresponding is-1, is expressed in V
New
Outside     }     addvnew[start]=0;                                        Add start point start to V
New
     Adjecent[start]=start;                                                      for (i=1;i<vnum-1;i++)                                             {        int min=max;        int v=-1;        for (j=1;j<vnum;j++)                                              {            if (addvnew[j]!=-1&&lowcost[j]<min)                 //In V
New
Find the shortest path            {                min=lowcost[j];                v=j;            }        }        if (v!=-1)        {            printf ("%d%d%d\n", Adjecent[v],v,lowcost[v]);            addvnew[v]=0;                                      The V Plus V
New
Medium            sumweight+=lowcost[v];                             Calculates the sum of the path lengths for            (j=1;j<vnum;j++)            {                if (Addvnew[j]==-1&&edge[v][j]<lowcost[j])                      {                    Lowcost[j]=edge[v][j];                     At this point the V point is added V
New
Need to update lowcost                    adjecent[j]=v                                             ;    }}}} printf ("The minmum weight is%d", sumweight);}

5. Complexity of Time

Number of vertices V, number of sides E

Adjacency Matrix: O (V2) adjacency table: O (elog2v)

Kruskal algorithm

1. Overview

The Kruskal algorithm is an algorithm for finding the smallest spanning tree, published by Joseph Kruskal in 1956. The prim algorithm and Boruvka algorithm are also used to solve the same problem. Three kinds of algorithms are the application of greedy algorithm. Unlike the Boruvka algorithm, the Kruskal algorithm is also effective when there are edges with the same weights in the diagram.

2. Simple description of the algorithm

1). Graph with v vertices, e-sides

2). The new diagram Graphnew,graphnew has the same e vertex in the original, but no edge

3). Sort all E edges in the original graph by weights from small to large

4). Loop: Expediency The least-valued edge begins to traverse each edge until all the nodes in the graph graph are in the same connected component

If the two nodes connected by this edge are not in the same connected component in Figure Graphnew

Add this edge to figure graphnew

Legend Description:

First step, we have a graph graph with a number of points and edges

The lengths of all edges are sorted, with the result of sorting as the basis for our selection of edges. This once again embodies the idea of the greedy algorithm. Resource sequencing, the selection of local optimal resources, sorting completed, we took the lead in selecting the side AD. So our diagram becomes the right image.

Look for the rest of the changes. We found the CE. The weight of the side is also 5.

And so on we find the 6,7,7, namely Df,ab,be.

Continue selection below, BC or EF Although now the length of the 8 edge is the smallest of the selected edges. But now they are connected (for BC you can connect via Ce,eb, and a similar EF can go through eb,ba,ad,df). So there's no need to choose them. Similar BD is already connected (here the connecting lines are in red).

Finally, eg and FG are left. Of course we have chosen eg. The final success chart is right:

3. Simple Proof Kruskal algorithm

The vertex number N of the graph is summed up, and the Kruskal algorithm is proved to be applicable to any n-order graph.

Inductive basis:

N=1, it is clear that the smallest spanning tree can be found.

Induction process:

Assuming that the Kruskal algorithm is applicable to the n≤k order, then, in the k+1 order G, we take the shortest side of the two endpoints A and b a merge operation, that is, you and V together to a point V ', the original connected to the side of the V ' up to V ' up, so that you can get a K-order G ' (u,v merge is 1 less one edge), the G ' minimum spanning tree T ' can be obtained using the Kruskal algorithm.

We prove T ' +{<u,v>} is the smallest spanning tree of G.

If T ' +{<u,v>} is not the minimum spanning tree, the minimum spanning tree is T, i.e. W (t) <w (t ' +{<u,v>}). It is obvious that T should contain <u,v> otherwise, you can add <u,v> to T to form a ring, delete any of the existing edges on the ring and form a spanning tree with a smaller weight. and T-{<u,v>}, is the generation tree of G '. So W (T-{<U,V>}) <=w (t '), which is W (t) <=w (t ') +w (<u,v>) =w (t ' +{<u,v>}), creates a contradiction. Therefore, the hypothesis is not established, T ' +{<u,v>} is the smallest spanning tree of G, and the Kruskal algorithm is applicable to k+1 order.

By the mathematical induction method, the Kruskal algorithm is proven.

4. Code algorithm implementation

typedef struct {char vertex[vertexnum];                       Vertex table int Edges[vertexnum][vertexnum];                                               Adjacency matrix, can be regarded as the side table int n,e;  The current number of vertices and the number of sides of}mgraph in the graph;                                                 typedef struct Node {int u;                                                 The starting vertex of the edge int v;                                                 End vertex of the Edge int w; The weight value of the edge}edge;      void Kruskal (Mgraph G) {int i,j,u1,v1,sn1,sn2,k;                                    int Vset[vertexnum];                                         Auxiliary array, determine whether two vertices are connected int e[edgenum];                                                    Store all the edges k=0; The subscript of the e array starts with 0 for (i=0;i<g.n;i++) {for (j=0;j<g.n;j++) {if (G.edges[i][j]                  !=0 && g.edges[i][j]!=inf) {e[k].u=i;E[k].v=j;                  E[K].W=G.EDGES[I][J];              k++;                            }}} heapsort (E,k,sizeof (e[0]));      Heap sort, by weight from small to large arrange for (i=0;i<g.n;i++)//Initialize auxiliary array {vset[i]=i;                                                   } k=1;                                                   The number of edges generated, the last is exactly the total number of edges j=0;          Subscript in E while (K&LT;G.N) {sn1=vset[e[j].u];                                  SN2=VSET[E[J].V];            To get the set number if the two vertices belong to the IF (SN1!=SN2)//not within the same set number, add the edge to the minimum spanning tree {                   printf ("%d--->%d,%d", E[J].U,E[J].V,E[J].W);              k++; for (i=0;i<g.n;i++) {if (VSET[I]==SN2) {vset[i]=s                  N1;      }}} j + +;   }  }


Time complexity: ELOG2E E is the number of edges in the graph

Minimum spanning tree-prim algorithm and Kruskal algorithm

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.