POJ 2560 浮点型的带权值

本文介绍了一种解决连接多个点并使总连线长度最短的问题的算法——最小生成树算法。该算法通过寻找一系列的直线连接所有点,同时确保使用的墨水总量最少,适用于诸如地图绘制等实际应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Freckles
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8309 Accepted: 3952

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.

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


#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct edge
{
    int x,y;
    float w;
}e[1000000];
int f[1000000];
float x[1000];
float y[1000];
int cmp(edge a,edge b)
{
    return a.w<b.w;
}
int find(int x)
{
    return f[x] == x ? x : (f[x] = find(f[x])); //并查集一步写完
}
int merge(int a,int b)
{
    int u,v;
    u=find(a);
    v=find(b);
    if(u!=v){
    f[v]=u;
    return 1;
}
return 0;
}
int main()
{
    int n;
    int cnt=0;
    scanf("%d",&n);
    for(int i=0;i<1000000;i++)
    {
        f[i]=i;
    }
    for(int i=0;i<n;i++)
    {
        scanf("%f%f",&x[i],&y[i]);
        for(int j=0;j<i;j++)
        {
            e[cnt].x=i;
            e[cnt].y=j;
            e[cnt].w=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
            cnt++;
        }
    }
    float ans=0;
    sort(e,e+cnt,cmp);
    for(int i=0;i<cnt;i++)
    {


           if(merge(e[i].x,e[i].y))
             ans+=e[i].w;
        }

    printf("%.2f",ans);

return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值