正题
题目链接:
http://poj.org/problem?id=2560
大意
有n个点,给出坐标,求连接这n个点的最短路线
解题思路
KURUSKAL算法求最小生成树。
代码
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
double xx[101],yy[101],sum;
int n,father[101],s,p;
struct line{int first,last;double w;
}a[10001];
double dis(double xx1,double yy1,double xx2,double yy2)
{return sqrt((xx1-xx2)*(xx1-xx2)+(yy1-yy2)*(yy1-yy2));
}//求距离
bool cmp(line xx,line yy)
{return xx.w<yy.w;
}
int find(int xx)
{if (father[xx]!=xx) return father[xx]=find(father[xx]);else return father[xx];
}//找祖先
void llll(int xx,int yy)
{father[find(xx)]=find(yy);
}//连接
int main()
{scanf("%d",&n);for (int i=1;i<=n;i++){scanf("%lf%lf",&xx[i],&yy[i]);}for (int i=1;i<n;i++)for (int j=i+1;j<=n;j++){a[++p].first=i;a[p].last=j;a[p].w=dis(xx[i],yy[i],xx[j],yy[j]);//加边}for (int i=1;i<=n;i++) father[i]=i;//初始化sort(a+1,a+1+p,cmp);//排序for (int i=1;i<=p;i++){if (find(a[i].first)!=find(a[i].last))//若没有连接{llll(a[i].first,a[i].last);//连接s++;//记录边数sum+=a[i].w;//记录价值}if (s==n-1) break;}printf("%0.2lf",sum);//输出
}