# hdoj1233

Problem : 1233 ( 还是畅通工程 )     Judge Status : Accepted
RunId : 2690843    Language : G++    Author : huwenbiao
Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
/***************************************************************\
*Author:Hu Wenbiao
*Created Time: Mon 26 Jul 2010 08:09:32 PM CST
*File Name: main.cpp
*Description:最小生成树。Kruscal算法
\***************************************************************/

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
/*----------------------*Global Variable*----------------------*/
int
parent[
110],N,M,sum;
struct
Edge{
int
from,to,dis;
}
edge[
5000];
//*=======================*Main Program*=======================*//
using namespace std;
bool
cmp(Edge a,Edge b){
return
a.dis<b.dis;
}

int
find(int x){
if
(parent[x]>
0)
parent[x]=find(parent[x]);
return
parent[x]>
0?parent[x]:x;
}

void
union_set(int x,int y){
x=find(x),y=find(y);
if
(parent[x]<parent[y]){
parent[x]+=parent[y];
parent[y]=x;
}

else
{
parent[y]+=parent[x];
parent[x]=y;
}
}

int
main(){

//freopen("input","r",stdin);
while(scanf("%d",&N)!=EOF&&N){
M=N*(N-
1)/2;
for
(int i=
0;i<M;i++){
scanf(
"%d%d%d",&edge[i].from,&edge[i].to,&edge[i].dis);
}

sum=
0;
memset(parent,-
1,sizeof(parent));
sort(edge,edge+M,cmp);
for
(int i=
0;N>1&&i<M;i++){
int
x=find(edge[i].from),y=find(edge[i].to);
if
(x!=y){
union_set(x,y);
sum+=edge[i].dis;
N--;
}
}

printf(
"%d\n",sum);
}
}
posted @ 2010-07-26 20:41  open source  阅读(187)  评论(0编辑  收藏