https://en.wikipedia.org/wiki/Kruskal%27s_algorithm
1 struct edgetype 2 { 3 int from; 4 int to; 5 int len; 6 }edge[100001]; 7 int n,m; 8 bool com(const edgetype& x,const edgetype& y) 9 { 10 return x.len<y.len; 11 } 12 int father[10001]; 13 int getfather(int x) 14 { 15 if(x==father[x]) 16 { 17 return x; 18 } 19 father[x]=getfather(father[x]); 20 return father[x]; 21 } 22 bool judge(int x,int y) 23 { 24 return getfather(x)!=getfather(y); 25 } 26 void merge(int x,int y) 27 { 28 x=getfather(x); 29 y=getfather(y); 30 father[x]=y; 31 return; 32 } 33 void init() 34 { 35 scanf("%d%d",&n,&m); 36 for(int i=1;i<=n;i++) 37 { 38 father[i]=i; 39 } 40 for(int i=1;i<=m;i++) 41 { 42 scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].len); 43 } 44 return; 45 } 46 int kruskal() 47 { 48 int res=0; 49 sort(edge+1,edge+1+m,com); 50 for(int i=1;i<=m;i++) 51 { 52 if(judge(edge[i].from,edge[i].to)) 53 { 54 res+=edge[i].len; 55 merge(edge[i].from,edge[i].to); 56 } 57 } 58 return res; 59 }