The Kruskal algorithm is greedy on the basis of the query set. It proves the correctness of the algorithm. After reading the introduction to the algorithm, I still don't know much about it. However, I feel that it is much easier to write than prim.
# Include <iostream> # include <vector> # include <algorithm> using namespace STD; Class node {public: int X; int y; int DIS ;}; bool CMP (node & LHS, node & RHs) {return LHS. dis <RHS. DIS;} int N; vector <node> way; vector <int> father; int find_father (int x) {If (x = Father [x]) return X; else {FATHER [x] = find_father (father [x]); // compression path} return father [X];} void Merge (int A, int B) {FATHER [a] = B;} int mst_kruskal () {int res = 0; sort (W Ay. begin (), way. end (), CMP); // greedy sorting int temp = N * (n-1)/2; for (INT I = 0; I <= N; I ++) {// initialize the parent node father. push_back (I) ;}for (INT I = 0; I <temp; I ++) {int FX = find_father (way [I]. x); int FY = find_father (way [I]. y); If (FX! = FY) {res + = way [I]. DIS; merge (FX, FY) ;}} return res ;}int main () {While (scanf ("% d", & N) == 1 & N) {int temp = N * (n-1)/2; for (INT I = 0; I <temp; I ++) {node; scanf ("% d", &. x, &. y, &. dis); way. push_back (a);} printf ("% d \ n", mst_kruskal (); way. clear (); // Clear father. clear () ;}return 0 ;}