还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 28842 Accepted Submission(s): 12893
当N为0时,输入结束,该用例不被处理。
代码:
#include<stdio.h>
struct path
{
int a; //a地
int b; //b地
int fee; //距离
};
struct path num[10000];
int father[10000],sum;
void sort(struct path num[],int n) //排序
{
struct path term;
int i,j,flag;
for(i=0; i<n; i++)
{
flag=i;
for(j=i+1; j<n; j++)
if(num[j].fee<num[flag].fee)
flag=j;
term=num[i];
num[i]=num[flag];
num[flag]=term;
}
}
int find(int a)
{
if(father[a]!=a)
father[a]=find(father[a]);
return father[a];
}
void merge(struct path pre)
{
int x,y;
x=find(pre.a);
y=find(pre.b);
if(x!=y)
{
father[x]=y;
sum+=pre.fee;
}
}
int main()
{
int n,i;
while(1)
{
scanf("%d",&n);
if(n==0)
break;
for(i=1; i<=n; i++)
father[i]=i;
for(i=0; i<n*(n-1)/2; i++)
scanf("%d%d%d",&num[i].a,&num[i].b,&num[i].fee);
sort(num,n*(n-1)/2);
sum=0;
for(i=0; i<n*(n-1)/2; i++)
merge(num[i]);
printf("%d
",sum);
}
return 0;
}