当前位置: 代码迷 >> 综合 >> Freckles 九度OJ 1144 POJ 2560 最小生成树模板题 Kruskal算法
  详细解决方案

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

热度:87   发布时间:2023-12-20 23:23:58.0

题目链接

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;
}