POJ 2560 Freckles

本文介绍了一种通过暴力计算所有点间距离并使用Kruskal算法构建最小生成树的方法。该方法适用于数据规模较小的情况,通过直接计算两点间的欧氏距离来构建边的权重,并逐步添加最短边构建最小生成树。

数据太水了,所以用暴力求的距离。

//
//  main.cpp
//  Richard
//
//  Created by 邵金杰 on 16/7/24.
//  Copyright © 2016年 邵金杰. All rights reserved.
//


#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=100+10;
struct node{
    float x,y;
}node[maxn];
struct edge{
    int u,v;
    float w;
    bool operator < (struct edge p)const{
        return w<p.w;
    }
}edge[maxn*maxn];
int pa[maxn*maxn];
int getroot(int a) {return pa[a]==a?a:pa[a]=getroot(pa[a]);}
float dis(int i,int j)
{
    float x1,y1,x2,y2;
    x1=node[i].x,y1=node[i].y;
    x2=node[j].x,y2=node[j].y;
    return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
int main()
{
    int n,cnt=0;
    float ans=0;
    scanf("%d",&n);
    for(int i=1;i<=n;i++) pa[i]=i;
    for(int i=0;i<n;i++) scanf("%f%f",&node[i].x,&node[i].y);
    for(int i=0;i<n;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            edge[cnt].u=i;
            edge[cnt].v=j;
            edge[cnt].w=dis(i,j);
            cnt++;
        }
    }
    sort(edge,edge+cnt);
    for(int i=0;i<cnt;i++)
    {
        int root1,root2;
        root1=getroot(edge[i].u);
        root2=getroot(edge[i].v);
        if(root1==root2) continue;
        pa[root2]=root1;
        ans+=edge[i].w;
    }
    printf("%.2f\n",ans);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值