Description
In an episode of the Dick Van Dyke show, little Richie connects the freckles on his Dad's back to form a picture of the Liberty Bell. Alas, one of the freckles turns out to be a scar, so his Ripley's engagement falls through.
Consider Dick's back to be a plane with freckles at various (x,y) locations. Your job is to tell Richie how to connect the dots so as to minimize the amount of ink used. Richie connects the dots by drawing straight lines between pairs, possibly lifting the pen between lines. When Richie is done there must be a sequence of connected lines from any freckle to any other freckle.
Consider Dick's back to be a plane with freckles at various (x,y) locations. Your job is to tell Richie how to connect the dots so as to minimize the amount of ink used. Richie connects the dots by drawing straight lines between pairs, possibly lifting the pen between lines. When Richie is done there must be a sequence of connected lines from any freckle to any other freckle.
Input
The first line contains 0 < n <= 100, the number of freckles on Dick's back. For each freckle, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the freckle.
Output
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the freckles.
Sample Input
3 1.0 1.0 2.0 2.0 2.0 4.0
Sample Output
3.41
/*
此题目测应该是个Prim算法
*/
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
#define maxn 108
int rank1[maxn];
int father[maxn];
int find(int x)
{
if(x == father[x]) return x;
return father[x] = find(father[x]);
}
struct Point
{
double x,y;
}point[maxn];
struct Edge
{
int from,to;
double len;
}edge[maxn*maxn];
bool cmp(Edge a,Edge b)
{
return a.len < b.len;
}
double qlen(Point a,Point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
void Union(int a,int b)
{
if(rank1[a] > rank1[b])
{
father[b] = a;
}
else if(rank1[a] == rank1[b])
{
father[b] = a;
rank1[a]++;
}
else father[a] = b;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF &&n)
{
for(int i=1;i<=n;i++) father[i] = i;
memset(rank1,0,sizeof(rank1));
for(int i=1;i<=n;i++)
{
scanf("%lf%lf",&point[i].x,&point[i].y);
}
int k = 1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i <= j)continue;
edge[k].from = i;
edge[k].to = j;
edge[k++].len = qlen(point[i],point[j]);
}
}
int z = 0;
double cost = 0;
sort(edge+1,edge+k,cmp);
for(int i=1;i<k;i++)
{
int uu = find(edge[i].from);
int vv = find(edge[i].to);
if(uu != vv)
{
Union(uu,vv);
cost += edge[i].len;
z++;
if(z == n-1)break;
}
}
printf("%.2lf\n",cost);
}
return 0;
}