1 #include <stdio.h> 2 #include <algorithm> 3 #include <iostream> 4 #define MAXN 10000 5 #define MAXM 50000 6 struct edge 7 { 8 int u,v,w; 9 }edges[MAXM]; 10 int parent[MAXN]; 11 int n,m; 12 int i,j; 13 14 //并查集 15 void UFset() 16 { 17 for(i=1;i<=n;i++) 18 parent[i]=-1; 19 } 20 int Find(int x) 21 { 22 int s; 23 for(s=x;parent[s]>=0;s=parent[s]) ; 24 while(s!=x) 25 { 26 int tmp=parent[x]; 27 parent[x]=s; 28 x=tmp; 29 } 30 return s; 31 } 32 void Union(int R1,int R2) 33 { 34 int r1=Find(R1),r2=Find(R2); 35 int tmp=parent[r1]+parent[r2]; 36 if(parent[r1]>parent[r2]) 37 { 38 parent[r1]=r2; 39 parent[r2]=tmp; 40 } 41 else 42 { 43 parent[r2]=r1; 44 parent[r1]=tmp; 45 } 46 } 47 //并查集 48 49 50 int cmp(const void *a,const void *b) 51 { 52 edge aa=*(const edge *)a; 53 edge bb=*(const edge *)b; 54 return aa.w-bb.w; 55 } 56 void Kruskal() 57 { 58 int sumweight=0; 59 int num=0; 60 int u,v; 61 UFset(); 62 for(i=0;i<m;++i) 63 { 64 u=edges[i].u;v=edges[i].v; 65 if(Find(u)!=Find(v)) 66 { 67 sumweight+=edges[i].w; ++num; 68 Union(u,v); 69 } 70 if(num>=n-1) break; 71 } 72 if(num<n-1) printf("-1\n"); 73 else printf("%d\n",sumweight); 74 } 75 76 int main() 77 { 78 int u,v,w; 79 while(scanf("%d",&n)!=EOF) 80 { 81 if(n==0) break; 82 m=(n*(n-1))/2; 83 for(int i=0;i<m;i++) 84 { 85 scanf("%d%d%d",&u,&v,&w); 86 edges[i].u=u; edges[i].v=v; edges[i].w=w; 87 } 88 qsort(edges,m,sizeof(edges[0]),cmp); 89 Kruskal(); 90 } 91 }