#include <cstdio>#include<algorithm>using namespacestd;Const intMAXV = +;Const intINF =0xFFFFFFF;structedge{intU,v,cost;} E[MAXV];BOOLCMP (Edge A,edge b) {returnA.cost <B.cost;}intFATHER[MAXV];intFindfather (intx) { intA =x; while(x! = father[x]) x=Father[x]; //Path Compression while(A! =Father[a]) { inttemp =A; A=Father[a]; Father[temp]=x; } returnx;} intKruskal (intNintm) { intans=0, numedge=0; for(intI=0; i<n;i++) father[i]=i; Sort (e,e+m,cmp); for(intI=0; i<m;i++) { intfau=Findfather (E[I].U); intfav=Findfather (E[I].V); if(fau!=FaV) {Father[fau]=FaV; Ans+=E[i].cost; Numedge++; if(numedge==n-1) Break; } } if(numedge!=n-1)return-1; returnans;}intMainvoid){ intM,n; scanf ("%d%d",&n,&m); for(intI=0; i<m;i++) scanf ("%d%d%d",&e[i].u,&e[i].v,&e[i].cost); intAns =Kruskal (n,m); printf ("%d", ans); return 0;} /*6 1 4 5 2 1 2 one 5 3 5 5 3 4 5 5 3output:11*/
Graph theory-kruskal algorithm-sparse graph