poj 2560最小生成树 prim

最小生成树算法实践
Freckles
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 5657 Accepted: 2899

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

分析:本题大意为有n个坐标点,求连接这些点所用的长度最小。 我们先假设这些点都互相连接我们也就可以得到一个图而且是个强连通图,每条边的长度我们可以由两点的坐标求的。当你抽象出这是个图时你就会笑了,哈哈题意就是最小生成树的定义。好吧我们开始从这个图中找出最小生成树,可以用prim也可以用kruskal本人认为这题用prim算法比较合适一下是我的代码(用g++交是ok的, 用c++就WA,你懂得大姨妈常驻poj了)

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int n, sum = 0, find1[101];
float dist = 0;
struct node
{
	float x;
	float y;
}coordinate[101];
struct line
{
	int a;
	int b;
	float dis;
}segment[6000];
bool cmp(line a, line b)
{
	return a.dis < b.dis;
}
int find_set(int x)
{
	if (x != find1[x])
	{
		find1[x] = find_set(find1[x]);
	}
	else
		return find1[x];
}
bool un(int x, int y)
{
	x = find_set(x);
	y = find_set(y);
	if ( x == y)
	{
		return false;
	}
	else
	{
		find1[x] = y;
	}
	return true;
}
void prim()
{
	int i, j, k = 0;
	for (i = 0; i< sum; i++)
	{
		if (un(segment[i].a, segment[i].b))
		{
			dist +=segment[i].dis;
		}
	}
	printf("%.2f\n",dist);
}
int main()
{
	int i, j;
	cin >> n;
	for (i = 0; i < n; i++)
	{
		cin >> coordinate[i].x >> coordinate[i].y;
		find1[i] = i;
	}
	for (i = 0; i< n; i++)
	{
		for (j = i; j < n; j++)
		{
			segment[sum].a = i;
			segment[sum].b = j;
			segment[sum++].dis = sqrt(pow((coordinate[i].x - coordinate[j].x), 2)+
				pow((coordinate[i].y - coordinate[j].y), 2));
		}
	}
	sort(segment, segment+sum, cmp);
	prim();
	return 0 ;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值