1 #include<string.h> 2 #include<stdio.h> 3 #include<algorithm> 4 using namespace std; 5 const int MAXN=200010; 6 struct Node{ 7 int s,e,dis; 8 }; 9 Node dt[MAXN]; 10 int cmp(Node a,Node b){ 11 return a.dis<b.dis; 12 } 13 int pre[MAXN],mi,tot; 14 int find(int x){ 15 int r=x; 16 while(r!=pre[r])r=pre[r]; 17 int i=x,j; 18 while(i!=r)j=pre[i],pre[i]=r,i=j; 19 return r; 20 } 21 int merge(Node a){ 22 int f1,f2; 23 if(pre[a.s]==-1)pre[a.s]=a.s; 24 if(pre[a.e]==-1)pre[a.e]=a.e; 25 f1=find(a.s);f2=find(a.e); 26 if(f1!=f2)pre[f1]=f2,mi+=a.dis; 27 } 28 int main(){ 29 int N,M; 30 while(~scanf("%d%d",&N,&M),N||M){mi=tot=0; 31 memset(pre,-1,sizeof(pre)); 32 for(int i=0;i<M;i++)scanf("%d%d%d",&dt[i].s,&dt[i].e,&dt[i].dis),tot+=dt[i].dis; 33 sort(dt,dt+M,cmp); 34 for(int i=0;i<M;i++){ 35 merge(dt[i]); 36 } 37 //printf("%d %d \n",tot,mi); 38 printf("%d\n",tot-mi); 39 } 40 return 0; 41 }
原文:http://www.cnblogs.com/handsomecui/p/4725631.html