Freckles_最小生成树

题目描述

    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.

输入描述:

    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.

输出描述:

    Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the freckles.
示例1

输入

复制
3
1.0 1.0
2.0 2.0
2.0 4.0

输出

复制
3.41
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#define N 1100
using namespace std;
int pre[N];
struct edge
{
    int start;
    int end;
    double cost;
}edges[6000];
struct node
{
    double x;
    double y;
}nodes[N];
bool cmp(edge a,edge b)
{
    return a.cost<b.cost;
}
double dis(node a,node b)
{
    double temp=pow((a.x-b.x),2)+pow((a.y-b.y),2);
    return sqrt(temp);
}
int find(int a)
{
    if(pre[a]==a)return a;
    else return find(pre[a]);
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
        {
            cin>>nodes[i].x>>nodes[i].y;
        }
        int size=0;//edge从0开始的
        for(int i=1;i<=n;i++)
        {
            for(int j=i+1;j<=n;j++)
            {
                edges[size].start=i;
                edges[size].end=j;
                edges[size++].cost=dis(nodes[i],nodes[j]);
            }
        }//转化为完全图
        sort(edges,edges+size,cmp);
        for(int i=1;i<=n;i++)
              pre[i]=i;
        double ans=0;
        for(int i=0;i<size;i++)
        {
            int t1=find(edges[i].start);
            int t2=find(edges[i].end);
            if(t1!=t2)
            {
                ans+=edges[i].cost;
                pre[t2]=t1;

            }
        }
        printf("%.2f\n",ans);



    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38030194/article/details/80770537
今日推荐