SDNUOJ-1370-Freckles-最小生成树

题目

题目链接

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个点,用线将它们全部连起来,求所有线长度之和最小的连接方法。

思路

最小生成树

每加入一个点,就分别与之前输入的点各增加一条边,最后共有1 + 2 + 3 + … + (n-1)条边,
边的长度使用勾股定理(c = sqrt(a^2 + b^2))求得
最后,使用Kruskal算法求得最小生成树。

#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>

using namespace std;

struct Point {
    double x, y;
};

struct Edge {
    int s, e;//开始、结束点的索引
    double dis;
};

bool cmp(Edge a, Edge b) {
    return a.dis < b.dis;
}

Point points[110];
Edge edges[10010];

int n;
int edgeCnt;
int pointCnt;

void addEdge(int aIndex, int bIndex) {
    Edge newE;
    newE.s = aIndex;
    newE.e = bIndex;

    Point a = points[aIndex];
    Point b = points[bIndex];

    double dis = pow(abs(a.x - b.x), 2) + pow(abs(a.y - b.y), 2);
    dis = sqrt(dis);
    newE.dis = dis;
    edges[edgeCnt++] = newE;
}

void addPoint(int x, int y) {
    Point newP;
    newP.x = x;
    newP.y = y;
    points[pointCnt++] = newP;
    for (int i = 0; i < pointCnt - 1; i++) {
        addEdge(i, pointCnt - 1);
    }
}

int father[110];

void initUF() {
    for (int i = 0; i < 110; i++)
        father[i] = i;
}

int Find(int x) {
    int r = x;
    while (r != father[r])
        r = father[r];
    return r;
}

void Union(int x, int y) {
    int xFa = Find(x);
    int yFa = Find(y);
    if (xFa != yFa)
        father[yFa] = xFa;
}

int main() {
    edgeCnt = 0;
    pointCnt = 0;

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        double a, b;
        scanf("%lf %lf", &a, &b);
        addPoint(a, b);
    }

    initUF();
    double ans = 0;

    sort(edges, edges + edgeCnt, cmp);

    for (int i = 0; i < edgeCnt; i++) {
        Edge ne = edges[i];
        int sFa = Find(ne.s);
        int eFa = Find(ne.e);
        if (sFa != eFa) {
            ans += ne.dis;
            Union(ne.s, ne.e);
        }
    }

    printf("%.2f", ans);

    return 0;
}

Azure99

底层码农,休闲音游玩家,偶尔写写代码

看看这些?

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注