(step 6.1.9)hdu 1162(Eddy's picture——最小生成树)

149 篇文章 0 订阅
146 篇文章 1 订阅

题目大意:输入一个整数n表示表示有n个点。在接下来的n行中,每行有两个整数x , y 。分别表示一个点的横坐标以及纵坐标。求距离最小的连线


解题思路:
1)二维----->>一维

for(i = 1 ; i <= n ; ++i){
			scanf("%lf%lf",&point[i].x,&point[i].y);
			point[i].id = i;
		}


2)求所有连线的长度

int count = 0;
		for(i = 1 ; i <= n ;  ++i){
			for(j = i+1 ; j <= n ; ++j){
				e[count].begin = point[i].id;
				e[count].end = point[j].id;
				e[count].weight = getDistance(point[i],point[j]);
				count++;
			}
		}


因为之前写过一篇博客已对这种题有较详细的解释,所以这里就不详细解释了


代码如下:

/*
 * 1162_1.cpp
 *
 *  Created on: 2013年8月27日
 *      Author: Administrator
 */

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;

struct edge{
	int begin;
	int end;
	double weight;
};

const int maxn = 600;
int father[maxn];
edge e[maxn*maxn];

int find(int x){
	if( x == father[x]){
		return x;
	}

	father[x] = find(father[x]);
	return father[x];
}

double kruscal(int count){
	int i;
	double sum = 0;

	for(i = 1 ; i < maxn ; ++i){
		father[i] = i;
	}

	for(i = 0 ; i < count ; ++i){
		int fx = find(e[i].begin);
		int fy = find(e[i].end);

		if(fx != fy){
			father[fx] = fy;
			sum += e[i].weight;
		}
	}

	return sum;
}

bool compare(const edge& a , const edge& b){
	return a.weight < b.weight;
}

struct Point{
	double x;
	double y;
	int id;
};

Point point[maxn];

double getDistance(const Point& p1 , const Point& p2){
	return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) );
}
int main(){
	int n;
	while(scanf("%d",&n)!=EOF){
		int i,j;
		for(i = 1 ; i <= n ; ++i){
			scanf("%lf%lf",&point[i].x,&point[i].y);
			point[i].id = i;
		}

		int count = 0;
		for(i = 1 ; i <= n ;  ++i){
			for(j = i+1 ; j <= n ; ++j){
				e[count].begin = point[i].id;
				e[count].end = point[j].id;
				e[count].weight = getDistance(point[i],point[j]);
				count++;
			}
		}

		sort(e , e + count , compare);

		double sum = kruscal(count);

		printf("%.2lf\n",sum);
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帅气的东哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值