1#include"stdio.h"2#include"stdlib.h"3 structEdge4 {5 intm;6 intN;7 intD;8}a[5010];9 intcmpConst void*a,Const void*B)//sort in ascending orderTen { One return((structedge*) a)->d-((structedge*) b)D; A } - intMainvoid) - { the inti,n,t,num,min,k,g,x[ -]; -printf"Please enter the number of vertices:"); -scanf"%d",&n); -t = n * (n-1) /2; + for(i=1; i<=n;i++) -x[i]=i; +printf"Please enter the starting endpoint and weight for each edge: \ n"); A for(i=0; i<t;i++) atscanf"%d%d%d", &A[I].M,&A[I].N,&A[I].D);//enter weights for each edge -Qsort (A,t,sizeof(a[0]), CMP); -min=num=0; - for(i=0; i<t && num < n-1; i++) - { - for(K=a[i].m;x[k]!=k;k=x[k])//determines the set where the starting point of a segment is located inx[k]=X[x[k]]; - for(G=a[i].n;x[g]!=g;g=x[g])//determines the collection where the end point of a segment is located tox[g]=X[x[g]]; + if(k!=g)//if the two endpoints of a line segment are in a different set - { thex[g]=K; *min+=a[i].d; $num++;Panax Notoginsengprintf"join edge in minimum spanning tree:%d%d\n", A[I].M,A[I].N); - } the } +printf"the weight of the minimum spanning tree is:%d\n", min); A return 0; the}
Implementation of Kruskal algorithm