练习四 1002

概述:在平面坐标系中给你一些孤立的点,求把这些点联系起来的最小路程。

思路:这是经典最小生成树问题的一个变种,因为点的坐标是Double型的,所以比较难像其他题一样用位置表示点的根节点,所以,要从新给每个输入的点分配一个ID,然后就转化为经典的问题了。在这里我采用的仍然是Kruskal算法。

感想:无。

#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
const int N = 105;
int father[N];
struct point
{
    double x,y;
    int root;
}p[N*N];
int find(int x)
{
	if (x != father[x])
		father[x] = find(father[x]);
	return father[x];
}
struct edge
{
	point a,b;
	double v;
}e[N*(N - 1) / 2];
int cmp(edge e1, edge e2)
{
	return e1.v<e2.v;
}

int main()
{
    //ifstream cin("aaa.txt");
    int n;
    cin>>n;
        for(int i=0;i<n;++i)
        {
            cin>>p[i].x>>p[i].y;
            p[i].root=i;
            father[i]=p[i].root;
        }
        int cnt=0;
        for(int i=0;i<n;++i)
            for(int j=i+1;j<n;++j)
            {
                e[cnt].a=p[i];
                e[cnt].b=p[j];
                e[cnt].v=sqrt(pow(p[i].x-p[j].x,2)+pow(p[i].y-p[j].y,2));
                ++cnt;
            }
        sort(e,e+n*(n-1),cmp);
        double ans=0;
        for(int i=0;i<n*(n-1);++i)
        {
            int x = find(e[i].a.root);
			int y = find(e[i].b.root);
			if (x != y)
			{
				ans += e[i].v;
				father[x] = y;
			}
        }
        printf("%.2lf\n",ans);
    
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值