Principle: Using the greedy algorithm. First of all edges according to weight in ascending order, each of the initial point is a tree (a tree node). After traversing the front edge of the current collector, the current edge xy, if x, y in our already in the minimum spanning tree, then skip this edge.
If the x, y does not have at least a minimum spanning tree in our, while adding the minimum spanning tree, and the tree that contains x and y are merged into a tree comprising a tree. (And using the combined set difference operation is completed)
Note: The code does not verify the correctness!
//Kruscal算法 2020年3月29日 21:41:19 //---------------------------------- vector<int> father; //并差集 void merge(int x,int y){ int x_father=get_father(x),y_father=get_father(y); father[x]=y_father; } int get_father(int x){ if(father[x]!=x){ return father[x]=get_father(father[x]); } return x; } //----------------------------------- struct Edge // the right side { int Point1; int Point2; int Weigh; Edge ( int X, int Y, int Z): Point1 (X), Point2 (Y), Weigh (Z) {} }; // - ---------------------------------- // find the right edge weighted undirected graph and MST int kruscal ( ) { int points; // points: points COUT << " number of input points: " << endl; CIN >> points; father.resize (points); for ( int= I 0 ; I <Points; ++ I) { Father [I] = I; } Vector <Edge> Edges; // Edges: set the right side of the int R & lt, S, T; the while (R & lt CIN >>> > S >> T) { edges.emplace_back (R & lt, S, T); } Sort (edges.begin (), edges.end (), [] ( const Edge A &, const Edge & B) { return a.weigh < b.weigh;}); // in accordance with small to large weight int RES; // right and MST int edge_cnt = 0 ; // have chosen the number of sides for (const Auto & Edge: Edges) { int P1 = edge.point1, P2 = edge.point2; IF (Father [P1] == Father [P2]) { // P1, P2 has joined the MST Continue ; } RES + = Edge. Weigh; // this is added with MST ++ edge_cnt; merge (P1, P2); // merge the two points IF (edge_cnt> = points- . 1 ) { // edge number is -1 point, completed the construction of the MST BREAK ; } } return RES; }