http://acm.hdu.edu.cn/showproblem.php?pid=1233
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #define INIT 0x7ffffff 5 int Graph[110][110]; 6 int vis[110],dis[110]; 7 int town,road; 8 int sum; 9 int count; 10 void prime() 11 { 12 memset(vis,0,sizeof(vis)); 13 memset(dis,INIT,sizeof(dis)); 14 int i,j; 15 int min; 16 sum=0; 17 count=1; 18 int now; 19 for(i=1;i<=town;i++) 20 dis[i]=Graph[1][i]; 21 for(j=2;j<=town;j++) 22 { 23 min=INIT; 24 for(i=2;i<=town;i++) 25 { 26 if(min>dis[i]&&vis[i]==0) 27 { 28 min=dis[i]; 29 now=i; 30 } 31 } 32 if(min!=INIT) 33 { 34 count++; 35 sum+=min; 36 vis[now]=1; 37 for(i=1;i<=town;i++) 38 { 39 if(vis[i]==0&&Graph[now][i]!=0&&dis[i]>Graph[now][i]) 40 dis[i]=Graph[now][i]; 41 } 42 } 43 else return; 44 } 45 } 46 int main() 47 { 48 int road; 49 int a,b,c; 50 while(~scanf("%d",&town),town) 51 { 52 road=town*(town-1)/2; 53 for(int i=1;i<=town;i++) 54 { 55 for(int j=1;j<=town;j++) 56 { 57 if(i==j) Graph[i][j]=0; 58 else Graph[i][j]=INIT; 59 } 60 } 61 for(int i=1;i<=town;i++) 62 { 63 for(int j=i+1;j<=town;j++) 64 { 65 scanf("%d%d%d",&a,&b,&c); 66 Graph[a][b]=c; 67 Graph[b][a]=c; 68 } 69 } 70 prime(); 71 if(count==town) 72 printf("%d\n",sum); 73 else printf("不用考虑?\n"); 74 } 75 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<stdlib.h> 3 int root[110]; 4 struct Node 5 { 6 int start; 7 int end; 8 int len; 9 }node[5010]; 10 int cmp(const void*x,const void*y) 11 { 12 return (*(Node*)x).len>(*(Node*)y).len?1:-1; 13 } 14 int find(int x) 15 { 16 int r=x; 17 while(r!=root[r]) 18 r=root[r]; 19 20 return r; 21 } 22 void merge(int x,int y) 23 { 24 int fx,fy; 25 fx=find(x); 26 fy=find(y); 27 if(fx!=fy) root[fx]=fy; 28 } 29 int main() 30 { 31 int n; 32 int m; 33 int k; 34 int a,b,c; 35 while(~scanf("%d",&n),n) 36 { 37 for(int i=1;i<=n;i++) 38 root[i]=i; 39 k=0; 40 m=n*(n-1)/2; 41 for(int i=0;i<m;i++) 42 { 43 scanf("%d%d%d",&a,&b,&c); 44 45 node[k].start=a; 46 node[k].end=b; 47 node[k].len=c; 48 k++; 49 50 } 51 int sum=0; 52 qsort(node,k,sizeof(node[0]),cmp);//node[0]写成node,囧。。。 53 for(int i=0;i<k;i++) 54 { 55 if(find(node[i].start)!=find(node[i].end)) 56 { 57 merge(node[i].start,node[i].end); 58 sum+=node[i].len; 59 } 60 } 61 62 int count=0; 63 for(int i=1;i<=n;i++) 64 root[i]=find(i); 65 for(int i=1;i<=n;i++) 66 if(root[i]==i) count++; 67 if(count>1) printf("DBL\n"); 68 else printf("%d\n",sum); 69 } 70 }