/*INPUT6101 2 3 each 4 3 5 4 5 6 6 6 6output15*/#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespacestd;Const intn=1e5;structnode{intu,v,w; BOOL operator< (ConstNode &c)Const { returnw<c.w;//indicates a sort with w from small to large}}t[n];intn,m;intp[1001];intChaintx) { //return X==p[x]?p[x]:cha (P[x]); if(x!=P[x]) {P[x]=cha (P[x]);//always find ancestors . } returnp[x];}intcl () {intsum=0, top=0; for(intI=0; i<m;i++)//start traversing from the first edge { intx=t[i].u; inty=t[i].v; X=cha (x); Y=cha (y); if(x!=y)//if not the same ancestor{p[x]=y;//One of the points as the ancestor of another, in order to prevent the formation of loopssum+=T[I].W; Top++;//number of bars of the cumulative connection line } if(top==n-1)returnSum//to make n points all connected, at least n-1 edges are required } return-1;//Unable to connect}intMain () { while(SCANF ("%d%d", &n,&m)!=eof)//n points, M edge { for(intI=1; i<=n;i++) P[i]=i;//and check the set start all initialized to itself for(intI=0; i<m;i++) {scanf ("%d%d%d", &T[I].U,&T[I].V,&T[I].W//represent the starting point, the end point, the weights respectively} sort (T,t+M);//ensure that the trailing numbers are the smallest of the currentprintf"%d\n", Cl ()); } return 0;}
Kruskal algorithm (template)