Freckles 九度OJ 1144 POJ 2560 最小生成树模板题 Kruskal算法

本文详细解析了最小生成树算法的应用场景,通过一个具体的题目,介绍了如何在平面上找到连接多个点的最短线路总长度。文章提供了完整的AC代码实现,并解释了算法的基本原理。

题目链接

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个点,给出每个点的坐标,现在需要添加一些线段使得这些点能够通过一系列的线段相连,求最小的线段总长度。

解题思路:
最小生成树模板题,将平面上的点抽象成图上的结点,将结点之间直接相连的线段抽象成连接结点的边,且权值为线段的长度。只是在开始求解最小生成树之前,需要根据输入信息把图建立起来。

AC代码:

#include<iostream>
#include<math.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
#define maxn 101
struct node {
	double x, y;
}list[maxn];
int tree[maxn];
int findroot(int x) {
	if (tree[x] == -1)return x;
	int tmp = findroot(tree[x]);
	tree[x] = tmp;
	return tmp;
}
bool unit(int a, int b) {
	int fa = findroot(a);
	int fb = findroot(b);
	if (fa != fb) {
		tree[fa] = fb;
		return true;
	}
	return false;
}
struct E {
	int from, to;
	double cost;
	bool operator < (const E &a) const {
		return cost < a.cost;
	}
}edge[6000];
double compute(node a, node b) {
	double tmp = (a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y);
	return sqrt(tmp);
}
void init() {
	for (int i = 1; i < maxn; i++) {
		tree[i] = -1;
	}
}
int main() {
	int n;
	while (cin >> n) {
		init();
		for (int i = 1; i <= n; i++) {
			cin >> list[i].x >> list[i].y;
		}
		int cnt = 0;
		for (int i = 1; i <= n; i++) {//将图建立起来
			for (int j = i + 1; j <= n; j++) {
				edge[++cnt].from = i; edge[cnt].to = j;
				edge[cnt].cost= compute(list[i], list[j]);
			}
		}
		sort(edge + 1, edge + 1 + cnt);
		double ans = 0.0;
		for (int i = 1; i <= cnt; i++) {
			if (unit(edge[i].from, edge[i].to)) {
				ans += edge[i].cost;
			}
		}
		printf("%.2f\n", ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值