HDU 1233 畅通工程2

//最基础的并查集 最小生成树
#include <stdio.h>
#include
<stdlib.h>
const int MAX = 101;
struct E{
int x,y,weight;
};
E edge[
5001];
int father[MAX];
int cmp(const void *d1, const void *d2){
return (*(E*)d1).weight - (*(E*)d2).weight;
}
void makeSet(int n){
for(int i = 0; i <= n; i++)
father[i]
= i;
}
int find(int x){
return father[x] == x ? x : father[x] = find(father[x]);
}
int main(){
int N,cost;
while(scanf("%d",&N) == 1){
if(N == 0)
break;
makeSet(N);
cost
= 0;
for(int i = 1; i <= N*(N-1)/2; i++){
scanf(
"%d%d%d",&edge[i].x,&edge[i].y,&edge[i].weight);
}
qsort(edge
+1,N*(N-1)/2,sizeof(E),cmp); //一开始写成edge 一直错 因为0号单元没用
for(int i = 1; i <= N*(N-1)/2; i++){
int x = find(edge[i].x);
int y = find(edge[i].y);
if(x != y ){
cost
+= edge[i].weight;
if(x > y)
father[x]
= y;
else
father[y]
= x;
}
}
printf(
"%d\n",cost);
}
return 0;
}
posted @ 2011-04-10 06:20  L..  阅读(117)  评论(0编辑  收藏  举报