数据结构实验之图论九:最小生成树
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
有n个城市,其中有些城市之间可以修建公路,修建不同的公路费用是不同的。现在我们想知道,最少花多少钱修公路可以将所有的城市连在一起,使在任意一城市出发,可以到达其他任意的城市。
Input
输入包含多组数据,格式如下。
第一行包括两个整数n m,代表城市个数和可以修建的公路个数。(n <= 100, m <=10000)
剩下m行每行3个正整数a b c,代表城市a 和城市b之间可以修建一条公路,代价为c。
Output
每组输出占一行,仅输出最小花费。
Example Input
3 2 1 2 1 1 3 1 1 0
Example Output
2 0
#include <stdio.h>
#include <stdlib.h>
int s[10005];
struct node{
int a;
int b;
int c;
}ct[10005];
int cmp(const void *x,const void *y)
{
return (*(struct node *)x).c > (*(struct node *)y).c ? 1: -1;
}
int find(int a)
{
if(s[a]==a)
return a;
else
{
s[a]=find(s[a]);
return s[a];
}
}
int join(int a,int b)
{
int t1,t2;
t1=find(a);
t2=find(b);
if(t1!=t2)
{
s[t2]=t1;
return 1;
}
return 0;
}
int main()
{
int n,m,i,sum,cost;
while(~scanf("%d%d",&n,&m))
{
sum=0;cost=0;
for(i=1;i<=n;i++)
s[i]=i;
for(i=0;i<m;i++)
{
scanf("%d%d%d",&ct[i].a,&ct[i].b,&ct[i].c);
}
qsort(ct,m,sizeof(ct[0]),cmp);
for(i=0;i<=m;i++)
{
if(join(ct[i].a,ct[i].b))
{
sum++;
cost+=ct[i].c;
}
if(sum==n-1)
break;
}
printf("%d\n",cost);
}
return 0;
}