今天算是真正写了一会最小生成树,以前都只是看看觉得,嗯,会了,就一闪而过。
参考代码:
http://acm.hdu.edu.cn/discuss/problem/post/reply.php?postid=6133&messageid=1&deep=0
(活着的意义……是在你快死的瞬间划过你脑海的那些事啊……——江南 《龙族》,继续文艺范,,感觉最喜欢龙族3)
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 5010
#define M 110
struct node{
int x,y;
double dis;
};
node edge[N];
int fa[M];
double x[M],y[M];
bool cmp(node a, node b){
return a.dis<b.dis;
}
int root(int x){
if(fa[x]==x){
return x;
}
else{
fa[x]=root(fa[x]);
return fa[x];
}
}
double min_tree(int n,int loca){
double ans=0;
int count=0;
for(int i=0;i<loca;i++){
int a=root(edge[i].x);
int b=root(edge[i].y);
if(a==b){
continue;
}
else{
ans+=edge[i].dis;
fa[b]=a;//注意这里应该是b,而不是edge[i].y
count++;
if(count==(n-1)){
return ans;
}
}
}
return ans;
}
int main(){
int n;
int loca;
while(scanf("%d",&n)!=EOF){
for(int i=0;i<n;i++){
scanf("%lf%lf",&x[i],&y[i]);
fa[i]=i;
}
loca=0;
for(int i=0;i<n-1;i++){//已验证,正确
for(int j=i+1;j<n;j++){
edge[loca].x=i;
edge[loca].y=j;
edge[loca++].dis=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
}
}
sort(edge,edge+loca,cmp);
printf("%.2lf\n",min_tree(n,loca));
}
return 0;
}