http://acm.hdu.edu.cn/showproblem.php?pid=1233
最小生成树,kruskal算法
1 #include<stdio.h> 2 #include<math.h> 3 #include<string.h> 4 #include<stdlib.h> 5 #include<iostream> 6 using namespace std; 7 const int N=5005; 8 struct stu{ 9 int u; 10 int v; 11 int w; 12 }p[N]; 13 int n,m; 14 int father[N]; 15 16 int cmp(const void *a,const void *b) 17 { 18 return (*(struct stu*)a).w > (*(struct stu*)b).w?1:-1; 19 } 20 int find(int x) 21 { 22 if(father[x]!=x) 23 father[x]=find(father[x]); 24 return father[x]; 25 } 26 int make(int a,int b) 27 { 28 int f1=find(a); 29 int f2=find(b); 30 if(f1!=f2) 31 { 32 father[f2]=f1; 33 return 1; 34 } 35 return 0; 36 } 37 int kruskal() 38 { 39 int cns=0,k=0; 40 for(int i=0;i<m;i++) 41 { 42 if(make(p[i].u,p[i].v)) 43 { 44 cns+=p[i].w; 45 k++; 46 } 47 if(k==n-1) 48 return cns; 49 } 50 return cns; 51 } 52 53 int main() 54 { 55 while(~scanf("%d",&n)) 56 { 57 if(!n) 58 break; 59 m=n*(n-1)/2; 60 for(int i=1;i<=n;i++) 61 father[i]=i; 62 for(int i=0;i<m;i++) 63 { 64 scanf("%d%d%d",&p[i].u,&p[i].v,&p[i].w); 65 } 66 qsort(p,m,sizeof(struct stu),cmp); 67 printf("%d ",kruskal()); 68 69 } 70 return 0; 71 }