题解 | #Freckles#

Freckles

https://www.nowcoder.com/practice/41b14b4cd0e5448fb071743e504063cf

#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>

using namespace std;

int father[1010];
int height[1010];

struct Dot {
    double x;
    double y;
};

struct Edge {
    int from;
    int to;
    double weight;
};

vector<Dot> v;
vector<Edge> G;

void Init(int n) {
    for (int i = 1; i <= n; i++) {
        father[i] = i;
        height[i] = 1;
    }
}


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


void Union(int x, int y, double weight, double &total) {
    x = find(x);
    y = find(y);
    if (x != y) {
        total += weight;
        if (height[x] < height[y]) {
            father[x] = y;
        } else if (height[x] > height[y]) {
            father[y] = x;
        } else {
            father[y] = x;
            height[x]++;
        }
    }

}

double getdis(Dot x, Dot y) {
    return pow((x.x - y.x) * (x.x - y.x) + (x.y - y.y) * (x.y - y.y), 0.5);
}

bool compare(Edge l, Edge r) {
    return l.weight < r.weight;
}


int main() {
    int n;
    scanf("%d", &n);
    Init(n);
    for (int i = 0; i < n; i++) {
        Dot d;
        scanf("%lf%lf", &d.x, &d.y);
        v.push_back(d);
    }
    for (int i = 0; i < v.size() - 1; i++) {
        Edge edge;
        for (int j = i + 1; j < v.size(); j++) {
            edge.from = i;
            edge.to = j;
            edge.weight = getdis(v[i], v[j]);
            G.push_back(edge);
        }
    }
    sort(G.begin(), G.end(), compare);
    double total = 0;
    for (int i = 0; i < G.size(); i++) {
        Union(G[i].from, G[i].to, G[i].weight, total);
    }
    printf("%.2lf\n", total);
    return 0;
}

全部评论

相关推荐

11-01 08:48
门头沟学院 C++
伤心的候选人在吵架:佬你不要的,能不能拿户口本证明过户给我。。球球了
点赞 评论 收藏
分享
无情咸鱼王的秋招日记之薛定谔的Offer:好拒信,偷了,希望有机会用到
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务