Data structure and algorithm series----minimum spanning tree (prim algorithm & Kruskal algorithm)

Source: Internet
Author: User

One: Prim algorithm

1. Overview
Primm algorithm (prim algorithm). An algorithm in graph theory. The smallest spanning tree can be searched in weighted connected graphs. This is the tree formed by the subset of edges that the algorithm searches for. Contains not only all the vertices in the connected graph (English: Vertex (graph theory)). And the sum of the weights of all its edges is also 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, 1959, Aizeg Dicos again discovered the algorithm.

So, on some occasions. The Primm algorithm is also known as the DJP algorithm, the Delphi algorithm, or the Primm-Rockwell algorithm.


2. Simple descriptive description of the algorithm
1). Input: A weighted connected graph. The vertex set is V and the edge set is E.
2). Initialize: Vnew = {x}. where x is any node in the Set V (the starting 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 set vnew, and V is not in the vnew set, and v∈v (assuming there are several edges that satisfy the foregoing conditions, which have the same weight. You can choose one of them);
B. Add v to the set vnew. The <u, v> edges are added to the set enew;
4). Output: Use the collection vnew and enew to describe the smallest spanning tree that is obtained by the narrative.


3. Description of the legend of the algorithm

legend Description not selectable options available selected (vnew)

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

- - -

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "height=" 168 "width=" ">       

Vertex D is arbitrarily selected as the starting point. Vertex A , B , E , and F are connected by A single edge to D .

A is the closest vertex to D , so
a and the corresponding edge AD are highlighted.

c, G a, B, E, F d

The next vertex is a recent vertex of distance D or A . B distance D is 9, distance A is 7,E is a,F is 6. So
f Distance D or A is recent, 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 is 8 from B . E is 7 from B , andG is 11 from F .
e Recently, so the vertex e is highlighted with the corresponding edge be.

No C, E, G A, D, F, B

Over here. The vertices available for selection are only C and G.

C is 5, andG is 9 from e . So select C,
And is highlighted with the side EC together.

No C, G A, D, F, B, E

Vertex G is the only remaining vertex. It is 11 from F . Distance e is 9,e is recent, so highlight G
and corresponding Edge EG.

No G A, D, F, B, E, C

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center "height=" 168 "width=" >

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


4. Simple Proof Prim algorithm
Disprove: If prim generates not the smallest spanning tree
1). Set prim to generate a tree of G0
2). If Gmin is present, the cost (Gmin) <cost (G0) exists in Gmin <u,v> does not belong to G0
3). Add <u,v> Add a ring to the G0, and <u,v> is not the longest edge of the ring (this is due to <u,v>∈gmin)
4). This contradicts the shortest edge of prim each generation
5). If it is not established. The proposition is to be proven.


Complete code such as the following:

Using the adjacency matrix to store the graph, set two arrays of Lowcost and Adjindex, the former representing the weight of the edge, the latter representing the corresponding lowcost the beginning of the edge.

#include <iostream>using namespace Std;int graph[20][20];//adjacency Matrix char * vertex;//save vertex int Prim (int&); int main () {/*6 10A B C D E F0 1 60 2 10 3 51 2 51 4 33 2 53 5 22 5 42 4 64 5 6*///////1. Number of vertices and arcs of the input graph cout << "Please enter the number of vertices and arcs of the graph:"; int Vexnum, arcnum;cin >> vexnum >> arcnum;//////2. Initialize adjacency matrix for (int i = 0; i < vexnum; i++) for (int j = 0; J &lt ; Vexnum; J + +) Graph[i][j] = int_max;//infinite/////3. Input vertices cout << enter << vexnum << vertex information: vertex = new Char[vexnum] ; for (int i = 0; i < vexnum; i++) cin >> VERTEX[I];//////4. Enter arc information (direction and weight of edge) cout << "Enter" << arcnum <& Lt "Information of an arc: \ n"; int A, B, c;for (int i = 0; i < Arcnum; i++) {cin >> a >> b >> c;graph[a][b] = c;graph[b][ A] = C;} 5. Output minimum spanning tree cout << "\ n \ nthe minimum tree is: \ n"; int x = Prim (vexnum); cout << "\ n min Right and =" << x << endl<<e Ndl;return 0;} int Prim (int & _vexnum)//prim minimum spanning tree {int * lowcost = new int[_vexnum];//save weight on edge int * Adjindex = new Int[_vexnum];for (int i = 1; i < _vexnum; i++) {lowcost[i] = graph[0][i];adjindex[i] = 0;} Lowcost[0] = 0;//z Here is a trick, the assignment of 0 means that the point has been added to the spanning tree, do not do processing, the equivalent of often encountered in the visited tag array, of course you can also assign a value of -1adjindex[0] = 0;int min, Minindex, sum=0;for (int i = 1; i < _vexnum; i++) {min = int_max;for (int j = 1; j < _vexnum; J + +)//Find the right value min {if (Lowcost[j] < Min && lowcost[j]!=0) {min = Lowcost[j];minindex = j;}} cout << Vertex[adjindex[minindex]] << "------>" << vertex[minindex] << endl;sum + = min; Lowcost[minindex] = 0;adjindex[minindex] = 0;for (int j = 1; j < _vexnum; J + +)//update lowcost and Adjindex array {if (Graph[minindex ][J] < Lowcost[j]) {lowcost[j] = graph[minindex][j];adjindex[j] = Minindex;}}} delete []lowcost;delete []adjindex;return sum;}

The above code is constructed with the following diagram:



Perform such as the following:



Two: Kruskal algorithm

1. Overview
The Kruskal 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 descriptive 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 image. But no side.
3). Sort all E edges in the original graph by weights from small to large
4). Loop: The expediency value of the smallest edge begins to traverse each edge. Until all the nodes in graph graph are in the same connected component, the two nodes connected by the if side are not in the same connected component in Figure Graphnew. Add this edge to figure graphnew.


3. Description of Legend

The first step first. We have a graph graph. There are several points and edges

Sorts the lengths of all the edges. Use the result of sorting as the basis for our selection of edges.

This once again embodies the idea of the greedy algorithm. Resource ordering. Select the local optimal resource, and after the sorting is finished. We are leading the selection of side AD.

So our diagram becomes the left-hand 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, DF. Ab,be.

The following continues to select, BC or EF Although today's 8-length edge is the smallest of the selected edges. But now they are connected (for BC to be able to connect via Ce,eb, a similar EF can be linked 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 left:




4. Simple Proof Kruskal algorithm
The vertex number N of the graph is summed up, proving that the Kruskal algorithm is suitable for random n-order graphs.
Inductive basis:
N=1. The smallest spanning tree can obviously be found.
Induction process:
If 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 U and V to go up, so that the line to get a K-order G ' (U,v of the merger is k+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.


With contradiction:

If T ' +{<u,v>} is not the minimum spanning tree, the minimum spanning tree is T, which is W (t) <w (t ' +{<u,v>}). Obviously t should include <u,v>. Otherwise, you can add <u,v> to T, form a ring, delete the original random side of the ring, forming a tree with a smaller weight value. 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. So if not, T ' +{<u,v>} is the smallest spanning tree of G. The Kruskal algorithm is also applicable to the K+1 order chart. By the mathematical induction method, the Kruskal algorithm is proven.



Code implementation:

The following code uses and check set, about and check the contents, please refer to: http://blog.csdn.net/laojiu_/article/details/50769868

#include <iostream> #include <algorithm>using namespace Std;struct edge//represents an edge {int u;//start vertex int v;//end vertex int w;//the weight value of the Edge};bool cmp (Edge edge1, Edge Edge2) {return (EDGE1.W < EDGE2.W);} edge* edge;//the array of storage edges int* father;int vexnum, arcnum;//vertices. The number of sides int Kruskal (); int Find (int x); void Join (int x, int y); int main () {/*6 100 1 60 2 10 3 51 2 51 4 33 2 53 5 22 5 42 4 64 5 6*/cout << "Please enter the number of vertices and arcs of the graph:"; Cin >> vexnum >> arcnum;father = new Int[vexnum];for (int i = 0; i < Vexnum; i++) Father[i] = i;cout << "Please enter the information for << arcnum <<": \ n "; edge = new Edge[arcnum];for (int i = 0; i < a Rcnum; i++) Cin >> edge[i].u >> edge[i].v >> edge[i].w;cout << Kruskal () << Endl;delete[]edge; Delete[]father;return 0;} int Find (int x) {return (x = = Father[x])? X:find (Father[x]);} void Join (int x, int y) {int root_x = find (x), int root_y = find (y), if (root_x! = root_y) father[root_x] = root_y;} int Kruskal () {int sum = 0;//Minimum path weight value and int finished = 0;//The edge of the minimum spanning treeThe number should be the vertex number-1, where the tag is set to complete the sort (edge, Edge + Arcnum, CMP); for (int i = 0; I < arcnum&&finished < vexNum-1; i++) {int Root_u = find (edge[i].u), int root_v = Find (EDGE[I].V), if (Root_u! = root_v) {Join (edge[i].u, edge[i].v); finished++; cout << edge[i].u << "----->" << edge[i].v << endl;sum + = EDGE[I].W;}} return sum;}

The data test in the code, convenient for the reader to test the correctness of the program. If there is an error. Please point out, thanks!



Return folder----> Data structures and Algorithms folder






References links and image resources from:

The data structure of the Min.

http://blog.csdn.net/yeruby/article/details/38615045.

Http://www.cnblogs.com/biyeymyhjob/archive/2012/07/30/2615542.html.

Data structure and algorithm series----minimum spanning tree (prim algorithm &amp; 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.