1. 程式人生 > >HDU-1233 還是暢通工程

HDU-1233 還是暢通工程

# include<stdio.h>
# include<string.h>
# include<algorithm>
using namespace std;
int fa[5006];



int find(int x){
	int r=x;
	while(r!=fa[r]){
		r=fa[r];
	}
	return r;
}
int join(int x,int y){
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy){
		fa[fx]=fy;
		return 1;
}
else{
	return 0;
}
}
struct node{
	int a,b,c;
}q[5006];
bool cmp(node x,node y){
	return x.c<y.c;
}

int main(){
	int n;
	while(scanf("%d",&n)!=EOF){
		if(n==0){
			break;
		}
		for(int i=1;i<=n;i++){
			fa[i]=i;
		}
		for(int i=1;i<=n*(n-1)/2;i++){
			scanf("%d %d %d",&q[i].a,&q[i].b,&q[i].c);
		}
		sort(q+1,q+n*(n-1)/2+1,cmp);
		int meony=0;
		for(int i=1;i<=n*(n-1)/2;i++){
			if(join(q[i].a,q[i].b)){
				meony=meony+q[i].c;
			}
		}
		printf("%d\n",meony);
	}
	return 0;
}