1 /*
2 先对边进行排序保证从小的边开始找,如果不合法即构成回路,
3 是不加入统计的,可以画图直观的来看一下。
4 */
5 #include<stdio.h>
6 #include<stdlib.h>
7 int bin[1000001];
8 int find(int x)
9 {
10 int r=x;
11 while(r!=bin[r])
12 r=bin[r];
13 return r;
14 }
15 int merge(int x,int y)
16 {
17 int fx=find(x);
18 int fy=find(y);
19 if(fx!=fy)
20 {
21 bin[fx]=fy;
22 return 1;
23 }
24 else
25 return 0;
26 }
27 struct node
28 {
29 int u,w,v;
30 }edg[100000];
31 int cmp(const void *a,const void *b)
32 {
33 struct node *c=(struct node *)a;
34 struct node *d=(struct node *)b;
35 return c->w-d->w;
36 }
37 int main()
38 {
39 int n,m,i,count;
40 while(scanf("%d %d",&n,&m)!=EOF)
41 {
42 for(i=0;i<=m;i++)
43 bin[i]=i;
44 for(i=0;i<m;i++)
45 scanf("%d %d %d",&edg[i].u,&edg[i].v,&edg[i].w);
46 qsort(edg,m,sizeof(struct node),cmp);
47 count=0;
48 for(i=0;i<m;i++)
49 {
50 if(merge(edg[i].u,edg[i].v))
51 count+=edg[i].w;
52 }
53 printf("%d\n",count);
54 }
55 return 0;
56 }