minimum spanning tree algorithm generates kruskal

kurskal algorithm is more suitable for sparse graphs

kruskal pseudocode:

. 1  int Kruskal () {
 2      so that the minimum spanning tree of the sum of edge weights ans, minimum spanning tree of the current number of sides num_edge;
 . 3      all sides by the edge weight from small to large;
 . 4      for (small to large to enumerate all side) {
 . 5          IF (current test at different sides of the two end points of the communication blocks) {
 6              the test is added with minimum spanning tree;
 . 7              ANS = + side of the right side of the test;
 8              current number of edges in the minimum spanning tree Num_Edge plus one;
 9              number of current is equal to the number of vertices minus side Num_Edge end of the cycle is 1;
 10          }
 . 11  
12 is      }
 13 is      return ANS;
 14 }

Implementation:

. 1  struct Edge {
 2      int U, V;             // two sides endpoint number 
. 3      int cost;             // edge weight 
. 4  } E [MAXV];
 . 5  
. 6  BOOL CMP (Edge A, Edge B) {
 . 7      return a.cost < b.cost;
 . 8  }
 . 9  int Father [MAXV]; // disjoint-set array
 10  
. 11  @ disjoint-set query function 
12 is  int findFather ( int X) {
 13 is      int A = X;
 14      the while (X =!Father [X]) {
 15          X = Father [X];
 16      }
 . 17  
18 is      // path compression 
. 19      the while ! (A = Father [A]) {
 20 is          int Z = A;
 21 is          A = Father [A];
 22 is          Father [Z] = X;
 23 is      }
 24  
25      return X;
 26 is  }
 27  
28  // number of edges kruskal function returns the minimum spanning tree of the right side and, for the number of vertices parameter n, m of FIG 
29  int kruskal ( int n , int m) {
 30      int ANS =0 , num_edge = 0 ;     // minimum sum of edge weights, the current number of spanning edges
 31      // initialize disjoint-set 
32      for ( int I = . 1 ; I <= n-; I ++ ) {
 33 is          Father [I] = I ;
 34      }
 35  
36      // all sides sort 
37 [      Sort (E, E + m, CMP);
 38 is      // traversing all edges 
39      for ( int I = 0 ; I <m; I ++ ) {
 40          int FAU = findFather (E [I] .u);         // query test set of edges where two root end 
41         int FAV = findFather (E [I] .v);
 42 is          IF (! FAU = FAV) {
 43 is              Father [FAV] = FAU;
 44 is              ANS + = E [I] .cost;
 45              num_edge ++ ;
 46 is              IF (== num_edge n-- . 1 ) BREAK ;     // if a tree has been built out of the loop 
47          }
 48      }
 49      IF (n-num_edge = -! . 1 ) return - . 1 ;         // when FIG none, returns -1 
50      the else  returnANS;         // otherwise the right side and the minimum spanning tree 
51 }

 

Guess you like

Origin www.cnblogs.com/hi3254014978/p/11497610.html