ZOJ1872Freckles(MST)

ZOJ Problem Set - 1872
Freckles Time Limit: 2 Seconds      Memory Limit: 65536 KB 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.


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.

Input contains multiple test cases. Process to the end of file.


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


先算出边数,然后Kruscal求解。。

/*************************************************************************
* author:crazy_石头
* algorithm:MST
* date:2013/09/29
**************************************************************************/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstdio>

#define N 1000

using namespace std;

struct Edge
{
    int a;
    int b;
    double weight;
    bool operator<(const  Edge &A)const
    {
        return weight<A.weight;
    }
};
 

struct point
{
    double x,y;
    double dist(point A)
    {
        double tmp=(x-A.x)*(x-A.x)+(y-A.y)*(y-A.y);
        return sqrt(tmp);
    }
}list[101];
 

int p[N];

int Find_set(int x)
{
    return p[x]==-1?x:p[x]=Find_set(p[x]);
}
 

int main()
{
    int a,b,n,i,j;
    Edge edge[6000];
    while(cin>>n)
    {
        for(i=1;i<=n;i++)
        {
            cin>>list[i].x>>list[i].y;
        }
        int size=0;
        for(i=1;i<=n;i++)
        {
            for(j=i+1;j<=n;j++)
            {
                edge[size].a=i;
                edge[size].b=j;
                edge[size].weight=list[i].dist(list[j]);
                size++;
            }
        }

        sort(edge,edge+size);
        memset(p,-1,sizeof(p));
        double ans=0;

        for(i=0;i<size;i++)
        {
            a=Find_set(edge[i].a);
            b=Find_set(edge[i].b);
            if(a!=b)
            {
                p[a]=b;
                ans+=edge[i].weight;
            }
        }
        printf("%.2lf\n",ans);
    }
    return 0;
}


你可能感兴趣的:(ZOJ1872Freckles(MST))