题目:http://acm.hdu.edu.cn/diy/contest_showproblem.php?pid=1009&cid=5825&hide=0
AC代码(C++):
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#define N 121
#define M 10000
using namespace std;
typedef struct
{
int x,y;
int w;
} edge;
edge e[M];
int father[N];
int sum;
int cmp(const void *a,const void *b)
{
//return ((edge *)a)->w - ((edge *)b)->w;
return (*(edge *)a).w - (*(edge *)b).w;//这里两种表示方法都是可以的。
}
/*bool cmp(const edge &x,const edge &y)
{
return x.w<y.w;
}*/
int find(int x)
{
if(x!=father[x])
father[x]=find(father[x]);
return father[x];
}
void Union(int x,int y,int w)
{
int fx = find(x);
int fy = find(y);
if(fx != fy){
father[fx] = fy;
sum += w;
}
}
int main()
{
int i,n,m;
int x,y,u,v;
while(cin>>n&&(n != 0))
{
m = n*(n-1)/2;
for(i = 1; i <= m; i++)
cin>>e[i].x>>e[i].y>>e[i].w;
for(i = 1; i <= n; i++)
father[i] = i;
qsort(e+1,m,sizeof(edge),cmp);//注意:前面定义i=1,所以这里是从e[1]开始的.
//sort(e+1,e+m,cmp);
sum = 0;
for(i = 1; i <= m; i++)
{
u = find(e[i].x);
v = find(e[i].y);
if(u != v)
Union(u,v,e[i].w);
}
cout<<sum<<endl;
}
return 0;
}
总结:
1.注释部分的代码都是正确的。这里用了qsort和sort这两种排序方法。
2.特别要注意qsort和sort这两个比较函数的写法,是不同的。