hdu1162

今天算是真正写了一会最小生成树,以前都只是看看觉得,嗯,会了,就一闪而过。

参考代码:

http://acm.hdu.edu.cn/discuss/problem/post/reply.php?postid=6133&messageid=1&deep=0

(活着的意义……是在你快死的瞬间划过你脑海的那些事啊……——江南 《龙族》,继续文艺范,大笑,感觉最喜欢龙族3)

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 5010
#define M 110

struct node{
    int x,y;
    double dis;
};
node edge[N];
int fa[M];
double x[M],y[M];

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

int root(int x){
    if(fa[x]==x){
        return x;
    }
    else{
        fa[x]=root(fa[x]);

        return fa[x];
    }
}

double min_tree(int n,int loca){
    double ans=0;
    int count=0;

    for(int i=0;i<loca;i++){
        int a=root(edge[i].x);
        int b=root(edge[i].y);
        
        if(a==b){
            continue;
        }
        else{
            ans+=edge[i].dis;
            fa[b]=a;//注意这里应该是b,而不是edge[i].y
            count++;
            if(count==(n-1)){
                return ans;
            }
        }
    }

    return ans;
}

int main(){
    int n;
    int loca;

    while(scanf("%d",&n)!=EOF){
        for(int i=0;i<n;i++){
            scanf("%lf%lf",&x[i],&y[i]);
            fa[i]=i;
        }

        loca=0;
        for(int i=0;i<n-1;i++){//已验证,正确
            for(int j=i+1;j<n;j++){
                edge[loca].x=i;
                edge[loca].y=j;
                edge[loca++].dis=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
            }
        }
        sort(edge,edge+loca,cmp);

        printf("%.2lf\n",min_tree(n,loca));
    }

    return 0;
}


转载于:https://www.cnblogs.com/ahahah/p/4918186.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值