剑鱼行动(克鲁斯卡尔算法)
题意
Description
给出N个点的坐标,对它们建立一个最小生成树,代价就是连接它们的路径的长度,现要求总长度最小。N的值在100以内,坐标值在[-10000,10000].结果保留二位小数
Input
5 ---------------5个点
0 0 ---------------5个点点的坐标
0 1
1 1
1 0
0.5 0.5
Output
2.83
分析
先算出点与点之间的距离
距离=sqrt(sqr(x[i]-x[j])+sqr(y[i]-y[j]))
var
n,i,j,k,q,p,t:longint;
tj,min:real;
x,y:array[0..200]of real;
f:array[0..200]of longint;
a:array[0..200,0..200]of real;
begin
readln(n);
for i:=1 to n do
readln(x[i],y[i]);
for i:=1 to n do
begin
for j:=1 to n do
begin
a[i,j]:=sqrt(sqr(x[i]-x[j])+sqr(y[i]-y[j]));
end;
end;
tj:=0;
for i:=1 to n do
f[i]:=i;
for k:=1 to n-1 do
begin
min:=maxlongint;
for i:=1 to n do
for j:=1 to n do
if (f[i]<>f[j])and(a[i,j]<min)and(a[i,j]<>0) then
begin
min:=a[i,j];
p:=j;
q:=i;
end;
tj:=tj+min;
t:=f[p];
for i:=1 to n do
if f[i]=t then f[i]:=f[q];
end;
write(tj:0:2);
end.