L i n k Link Link
D e s c r i p t i o n Description Description
给出N个点的坐标,对它们建立一个最小生成树,代价就是连接它们的路径的长度,现要求总长度最小。N的值在100以内,坐标值在[-10000,10000].结果保留二位小数
I n p u t Input Input
5
0 0
0 1
1 1
1 0
0.5 0.5
O u t p u t Output Output
2.83
T r a i n Train Train o f of of T h o u g h t Thought Thought
用
K
r
u
s
k
a
l
Kruskal
Kruskal算法做,首先先用勾股定理求出点之间的距离,再做算法运算就可以了
不懂
K
r
u
s
k
a
l
Kruskal
Kruskal算法的可以看一下我之前的
b
l
o
g
blog
blog
C o d e Code Code
#include<cmath>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int father[101],n;
double x,y,a[10001][10001];
struct node
{
double from,now,time;
}f[10001];
bool cmp(node xx,node yy)
{
return xx.time<yy.time;
}
int find(int x)
{
if (father[x]==x) return x;
else return father[x]=find(father[x]);
}//寻找父节点
void merge(int x,int y)
{
int xx=find(x);
int yy=find(y);
if (xx<yy) father[xx]=father[yy];
else father[yy]=father[xx];
}//合并
int main()
{
int t=0;
scanf("%d",&n);
for (int i=1; i<=n; ++i) father[i]=i;
for (int i=1; i<=n; ++i)
scanf("%lf%lf",&x,&y),a[i][0]=x,a[i][1]=y;
for (int i=1; i<=n; ++i)
for (int j=1; j<i; ++j)
{
double xx=(double)(a[i][0]-a[j][0]);
double yy=(double)(a[i][1]-a[j][1]);
double ll=(double)sqrt(xx*xx+yy*yy);
f[++t]=(node){i,j,ll};//记录连边
}
int k=0;
double ans=0;
sort(f+1,f+t+1,cmp);
for (int i=1; i<=t; ++i)
{
if (find(f[i].from)!=find(f[i].now)) {
merge(f[i].from,f[i].now);
ans+=(double)f[i].time;
++k;
}
if (k==n-1) break;
}
printf("%.2lf",ans);
}