题解 | #Freckles#

Freckles

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

Kruskal算法,并查集,最小生成树

把每个边按照权值排序,从小到大依次把一条边上的两个不在同一个连通分量的顶点加入最小生成树

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const int N=100;

int father[N]; //父结点
int height[N]; //高度
struct Node{
    int value; //给每个结点的值,i从0到n-1
    double x; //结点坐标
    double y;
};
Node node[N];
struct Edge{
    int from;
    int to;
    double length; //两个结点之间的距离
};
vector<Edge> edge;
bool Compare(const Edge& a,const Edge& b){
    return a.length<b.length;
}
//初始化
void init(int n){
    for(int i=0;i<n;i++){
        father[i]=i;
        height[i]=0;
    }
    edge.clear();
}
//查找根结点
int Find(int x){ 
    if(x!=father[x]){
        father[x]=Find(father[x]);
    }
    return father[x];
}
void Union(int a,int b){
    int x=Find(a);
    int y=Find(b);
    if(x!=y){
        if(height[x]>height[y]){
            father[y]=x;
        }
        else if(height[x]<height[y]){
            father[x]=y;
        }
        else{
            father[y]=x;
            height[x]++;
        }
    }
}
//判断两个结点是否在一个连通分量中
bool judge(int a,int b){
    if(Find(a)==Find(b)) return true;
    else return false;
}
void appendedge(Node a,Node b){
    Edge temp;
    temp.from=a.value;
    temp.to=b.value;
    double x1,x2,y1,y2;
    x1=a.x;
    x2=b.x;
    y1=a.y;
    y2=b.y;
    double result=sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
    temp.length=result;
    edge.push_back(temp);
}
double Kruskal(int n){
    double result;
    //按照距离排序
    sort(edge.begin(),edge.end(),Compare);
    for(int i=0;i<edge.size();i++){
        if(judge(edge[i].from,edge[i].to)){
            continue;
        }
        Union(edge[i].from, edge[i].to);
        result+=edge[i].length;
    }
    return result;
}
int main() {
    int n;
    while(cin>>n){
        init(n);
        for(int i=0;i<n;i++){
            node[i].value=i;
            cin>>node[i].x>>node[i].y;
        }
        for(int i=0;i<n-1;i++){
            for(int j=i+1;j<n;j++){
                appendedge(node[i],node[j]);
            }
        }
        //kruskal
        double totallength=Kruskal(n);
        printf("%.2f\n",totallength);
    }
    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 12:31
以前小时候我最痛恨出轨、偷情的人,无论男女,为什么会出轨?现在我成了自己最讨厌的人,没想到分享的东西在牛客会被这么多人看,大家的评价都很中肯,我也认同,想过一一回复,但我还是收声了,我想我应该说说这件事,这件事一直压在我心里,是个很大的心结,上面说了人为什么出轨,我大概能明白了。我们大一下半年开始恋爱,开始恋爱,我给出了我铭记3年的承诺,我对她好一辈子,我永远不会背叛,我责任心太重,我觉得跟了我,我就要照顾她一辈子,我们在一起3年我都没有碰过她,她说往东我就往东,她说什么我做什么,她要我干什么,我就干什么!在学校很美好,中途也出过一些小插曲,比如男闺蜜、男闺蜜2号等等等。但我都强迫她改掉了,我...
牛客刘北:两个缺爱的人是没有办法好好在一起的,但世界上哪有什么是非对错?你后悔你们在一起了,但是刚刚在一起的美好也是真的呀,因为其他人的出现,你开始想要了最开始的自己,你的确对不起自己,21岁的你望高物远,你完全可以不谈恋爱,去过你想要的生活,你向往自由,在一起之后,你要想的不是一个人,而是两个人,你不是变心了,就像你说的,你受够了,你不想包容了,冷静几天是你最优的选择,爱人先爱己。
社会教会你的第一课
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务