# Prim algorithm and Kruskal algorithm for minimum spanning tree

Source: Internet
Author: User

For some cities to build roads or bridge problems, we need to complete the task at the minimum cost, look at the code of others, the idea is actually almost, but not good understanding, such as Kruskal algorithm in the use of recursion to realize whether the formation of the ring, I am dull, not figured ... Now even if you do it again, help yourself to comb it.
These two pieces of code has been through my debugging, to be able to run flawlessly, I hope to help everyone.

(1) Prim algorithm

The prim algorithm actually belongs to the greedy algorithm, each step, traversal is to find the most needed point, that is, the smallest adjacency edge, which is actually the same as the search for the shortest path of the single source Dijkstra algorithm, but in the update of each point path weights when the processing method is not the same, after all, the purpose is different. The idea of the prim algorithm is to select the shortest edge that has not been accessed and adjacent to the starting point from the starting point, then place the adjacency point as accessed, record the point, and then update the distance weights for the points that have been placed for the access: if the new POS point is at a distance from `map[pos][j]` the other adjacent and inaccessible points is less than the starting point of the previous distance `low[j]` , you need to update low[j], because LOW[J] always saves the shortest distance from the marked point. Nonsense not much to say, directly on the code.

``#include <iostream>using namespace STD;#define MAXINT 9999//maximum weight #define N//maximum fixed-point number intNMapN [N],low[n],visited[n];intPrim () {intpos,result=0;memset(Visited,0,sizeof(visited));//All points are not accessedvisited =1;//Starting from the first pointpos =1; for(intI=1; i<=n;i++) {if(i!=pos) Low[i] =Map[POS] [i];//low[] Initialize} for(intI=1; i<n;i++)//Recycle n-1 times because the first point has been determined{intTMP = MAXINT; for(intj=1; j<=n;j++)//Find adjacency minimum weight point{if(visited[j]==0&& low[j]<tmp) {tmp = Low[j];            pos = j; }} Visited[pos] =1;//New minimum weight pointresult + = TMP;//Record weights and         for(intj=1; j<=n;j++)//Update weights{if(visited[j]==0&& low[j]>Map[POS] [j]) {Low[j] =Map[POS]            [j]; }        }    }returnResult;}voidPrintmatrix () { for(intI=1; i<=n;i++) { for(intj=1; j<=n;j++) {cout<<MapI [j];if(j==n) {Continue; }cout<<" "; }cout<<endl; }}//In order to facilitate unified data entry, the data is stored in a txt text/*6 1 2 6 1 3 1 1 4 5 2 3 5 2 5 3 3 4 5 3 5 6 3 6 4 4 6 2 5 6 6 *intMain () {Freopen ("Primdata.txt","R", stdin);intLenCin>>n>>len;/ * Here by the way, before my mistake, the memset function is not very understanding, the beginning of the use of the memset (map,maxint,sizeof (map)), found that the printed value is very wrong, the original memset can only store data 0.* /     for(intI=1; i<=n;i++) { for(intj=1; j<=n;j++) {MapI [j] = MaxInt;//The weights are set to the maximum value first}    }intP,q,weight; for(intI=1; i<=len;i++) {Cin>>p>>q>>weight;//Modify weights according to graph        Map[P] [Q] =Map[Q] [P] = weight;//No direction diagram} Printmatrix ();intres = Prim ();cout<<"minimum weight and ="<<res<<endl; System"Pause");return 0;}``

(2) Kruskal algorithm

The Kruskal algorithm differs from the prim algorithm, the prim algorithm mainly relies on the node, so it is suitable for dense graphs, the algorithm complexity is O (n^2), and the Kruskal algorithm relies on the processing of the edge, so the application and sparse graph, anyway is less than the graph bar, algorithm complexity of O (Nlogn ), the main difference between the two algorithms is that the latter is the first to all the edge according to the weight of the order, at the same time applicable to the same weight value, and then the weight of the edge from small to large splicing, stitching on the basis is to see if it can form a ring, if possible, then discard the edge, continue to deal with the next A minimum spanning tree is formed. The picture here is too lazy to draw, borrow a picture of others.
The source address for this section is http://blog.chinaunix.net/uid-25324849-id-2182925.html, which resolves some issues.

The following is the code:

``#include <iostream>using namespace STD;#define MaxLen#define NintN,len;//Vertex count and number of edgesintFather[n];//Define parent node arraystructEdge//using a structure to store edges and two nodes of information{intx, y;//two adjacency points    intW;} E[maxlen];voidFather_initialize ()//Initialize the nodes for each edge, and the parent node initializes the{ for(intI=1; i<=n;i++) {father[i] = i; }}BOOLIs_same (intIintJ//Determine if the two nodes of an edge have the same parent node{ while(father[i]!=i)//Find parent node{i = father[i]; } while(FATHER[J]!=J)    {j = father[j]; }returnI==j?true:false;}voidUnion_group (intIintJ//To process the newly added edge, unifying the parent node{if(i>j) swap (I,J);//fixed order to ensure node order from small to large     while(I!=father[i])    {i = father[i]; } while(J!=father[j])//{j = father[j]; } Father[j] = i;The parent node of the//j is set to I, which is the final parent node}intSORTCMP (Const void*a,Const void*B)//comparison function for edge ordering of Qsort (){Edge AA = * (Constedge*) A; Edge BB = * (Constedge*) b;returnAA.W-BB.W;}/*//kruskaldata.txt data, data and Primdata.txt, description results 6 10 1 2 6 1 3 1 1 4 5 2 3 5 2 5 3 3 4 5 3 5 6 3 6 4 4 6 2 5 6 6 */intMain () {intresult =0; Freopen ("Kruskaldata.txt","R", stdin);Cin>>n>>len; for(intI=1; i<=len;i++) {Cin>>e[i].x>>e[i].y>>e[i].w; } qsort (E,len,sizeof(Edge), sortcmp); Father_initialize (); for(intI=1; i<=len;i++) {if(! Is_same (E[I].X,E[I].Y))//If the ring cannot be formed, the condition is met{result + = E[I].W;cout<<"Edge"<<i<<" : "<<e[i].x<<" ,"<<e[i].y<<endl;        Union_group (E[I].X,E[I].Y); }    }cout<<"minimum weight and ="<<result<<endl; System"Pause");return 0;}``

Would like to continue to write the Dijkstra algorithm, but found that seems to be inconsistent with the title, the next time to write it, I first write a blog, understand the problem may not be in place, if there are errors or need to improve the place, but also hope to put forward, not very grateful!

Prim algorithm and Kruskal algorithm for minimum spanning tree

Related Keywords:

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.