题解 | #Freckles 并查集#

Freckles

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

#include "bits/stdc++.h"
using namespace std;
int father[5000];
int height[5000];
struct Edge{
    int begin;
    int end;
    double cost;
};
struct Point{
    double x;
    double y;
};
void Inti(){
    for (int i = 0; i < 5000; ++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){
    int x_father = Find(x);
    int y_father = Find(y);
    if(height[x_father]>height[y_father]){
     father[y_father] = x_father;
    } else if(height[x_father]<height[y_father]){
        father[x_father] = y_father;
    }else{
        father[y_father] = x_father;
        height[x_father]++;
    }
}

bool compare1(Edge x,Edge y){
    return x.cost<y.cost;
}
int main() {
    int n;
    while (scanf("%d",&n)!=EOF){
        if(n==0){ break;}
        Inti();
        double answer = 0;
        Edge edge[n*(n-1)/2];
        Point points[n];
        for (int i = 0; i < n; ++i) {
            scanf("%lf%lf",&points[i].x,&points[i].y);
        }
        int count=0;
        for (int i = 0; i < n; ++i) {
            for (int j = i+1; j < n; ++j) {
                edge[count].begin=i;
                edge[count].end=j;
                edge[count].cost = sqrt((points[i].x-points[j].x)*(points[i].x-points[j].x)+(points[i].y-points[j].y)*(points[i].y-points[j].y));
                count++;
            }
        }
        sort(edge,edge+n*(n-1)/2,compare1);
        for (int i = 0; i < n*(n-1)/2; ++i) {
            if(Find(edge[i].begin)!=Find(edge[i].end)){
                Union(edge[i].begin,edge[i].end);
                answer+=edge[i].cost;
            }
        }
        printf("%.2lf\n",answer);

    }
    return 0;
}

全部评论

相关推荐

Yushuu:你的确很厉害,但是有一个小问题:谁问你了?我的意思是,谁在意?我告诉你,根本没人问你,在我们之中0人问了你,我把所有问你的人都请来 party 了,到场人数是0个人,誰问你了?WHO ASKED?谁问汝矣?誰があなたに聞きましたか?누가 물어봤어?我爬上了珠穆朗玛峰也没找到谁问你了,我刚刚潜入了世界上最大的射电望远镜也没开到那个问你的人的盒,在找到谁问你之前我连癌症的解药都发明了出来,我开了最大距离渲染也没找到谁问你了我活在这个被辐射蹂躏了多年的破碎世界的坟墓里目睹全球核战争把人类文明毁灭也没见到谁问你了😆
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务