--kruskal algorithm for minimum spanning tree

Source: Internet
Author: User
Tags new set

Given an Kruskal graph with weighted values, a spanning tree that requires the sum of weights is the most commonly used algorithm with the algorithm of prim. This article first introduces the Kruskal algorithm.

The basic idea of the Kruskal algorithm is that all edges are sorted by weight from small to large, then each edge is selected sequentially, and if the two endpoints of an edge are not in the same set, the two endpoints are merged into the same set, and if the two endpoints are in the same set, the two endpoints are connected to each other. The current edge is discarded; when all vertices are in the same set, the minimum spanning tree is formed. (all sides are traversed once the code is written)

Take a look at an example:

Steps:

(1) Sort the edges first according to the weights:

AD 5

CE 5

DF 6

AB 7

Be 7

BC 8

EF 8

BD 9

EG 9

FG 11

(2)

Select the ad edge, add a, d to the same set 1

Select the CE side, add C, E to the same set 2 (different from the collection of AD)

Select the edge of DF, since D is already in Set 1, so add F to the set 1, the collection becomes a, D, F

Select AB this side, similarly, set 1 becomes a, B, D, F

Select be this side, because B in set 1, E in Set 2, so the two collections are merged to form a new set abcdef

Because E, F is already in the same set, discard the BC this edge, similarly abandon the EF, BD

Select the eg edge, at which point all elements are already in the same set, and the minimum spanning tree forms

And symbolically discard the FG side.

The implementation code is as follows:

#include <iostream>#include<cstring>#defineMaxSize 20using namespacestd;structedge{intbegin; intend; intweight; }; structgraph{CharVer[maxsize +1]; intedg[maxsize][maxsize];};voidCreategraph (Graph *g) {intVertexnum; CharVer; inti =0; cout<<"Enter the vertices of the graph:"<<Endl;  while(Ver = GetChar ())! ='\ n') {g->ver[i] =Ver; I++; } g->ver[i] =' /'; Vertexnum= strlen (g->ver); cout<<"enter the corresponding adjacency matrix"<<Endl;  for(inti =0; i < Vertexnum; i++) {         for(intj =0; J < Vertexnum; J + +) {cin>> g->edg[i][j];//input 0 is not a side connection.        }    }}voidprintgraph (Graph g) {intVertexnum =strlen (G.ver); cout<<"the vertices of the graph are:"<<Endl;  for(inti =0; i < Vertexnum; i++) {cout<< G.ver[i] <<" "; } cout<<Endl; cout<<"the adjacency matrix of the graph is:"<<Endl;  for(inti =0; i < Vertexnum; i++) {         for(intj =0; J < Vertexnum; J + +) {cout<< G.edg[i][j] <<" "; } cout<<Endl; }}intGetvernum (Graph g) {returnstrlen (g.ver);}intGetedgenum (Graph g) {intres =0; intVertexnum =Getvernum (g);  for(inti =0; i < Vertexnum; i++) {        //The adjacency matrix is symmetric, the upper triangular elements are computed and can be         for(intj = i +1 /*Assuming that you don't point to yourself*/; J < Vertexnum; J + +) {            if(G.edg[i][j]! =0) res++; }    }        returnRes;} Edge*createedges (Graph g) {intK =0; intEdgenum =Getedgenum (g); intVertexnum =Getvernum (g); Edge* p =NewEdge[edgenum];  for(inti =0; i < Vertexnum; i++) {         for(intj = i; J < Vertexnum; J + +) {            if(G.edg[i][j]! =0) {P[k].begin=i; P[k].end=J; P[k].weight=G.edg[i][j]; K++; }        }    }     for(inti =0; I < edgenum-1; i++) {Edge Minweightedge=P[i];  for(intj = i +1; J < Edgenum; J + +) {            if(Minweightedge.weight >p[j].weight) {Edge temp=Minweightedge; Minweightedge=P[j]; P[J]=temp; }} P[i]=Minweightedge; }    returnp;}voidKruskal (Graph g) {intVertexnum =Getvernum (g); intEdgenum =Getedgenum (g); Edge*p =Createedges (g); int*index =New int[Vertexnum];//The index array whose elements are the number of the connected component, Index[i]==index[j] indicates that the vertices numbered I and J are in the same connected component    int*mstedge =New int[Vertexnum-1];//The number of the * * edges used to store the identified minimum spanning tree * *, total VertexNum-1 edge    intK =0; intWeightSum =0; intIndexbegin, Indexend;  for(inti =0; i < Vertexnum; i++) {Index[i]= -1;//Initialize all index to-1    }     for(inti =0; I < vertexnum-1; i++) {         for(intj =0; J < Edgenum; J + +) {            if( ! (Index[p[j].begin] >=0&& Index[p[j].end] >=0&& Index[p[j].begin] = = Index[p[j].end]/*If set up indicates that P[j].begin and P[j].end are already in the same connected block (and can reach each other, nonsense)*/) ) {Mstedge[i]=J; if(Index[p[j].begin] = =-1&& Index[p[j].end] = =-1) {Index[p[j].begin]= Index[p[j].end] =i; }                Else if(Index[p[j].begin] = =-1&& Index[p[j].end] >=0) {Index[p[j].begin]=i; Indexend=Index[p[j].end];  for(intn =0; n < Vertexnum; n++) {                        if(Index[n] = =indexend) {Index[n]==i; }                    }                }                Else if(Index[p[j].begin] >=0&& Index[p[j].end] = =-1) {Index[p[j].end]=i; Indexbegin=Index[p[j].begin]; /*Merge the connected components (or add the vertices without the connected component and change the value of the original connected component)*/                     for(intn =0; n < Vertexnum; n++) {                        if(Index[n] = =Indexbegin) {Index[n]==i; }                    }                }                Else{Indexbegin=Index[p[j].begin]; Indexend=Index[p[j].end];  for(intn =0; n < Vertexnum; n++) {                        if(Index[n] = = Indexbegin | | index[n] = =indexend) {Index[n]=i; }                    }                }                 Break; } }} cout<<"the side of the MST is:"<<Endl;  for(inti =0; I < vertexnum-1; i++) {cout<< G.ver[p[mstedge[i]].begin] <<"--"<< G.ver[p[mstedge[i]].end] <<Endl; WeightSum+=P[mstedge[i]].weight; } cout<<"the weight of the MST is:"<< WeightSum <<Endl;}

--kruskal algorithm for minimum spanning tree

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.