HDU 1162 Eddy's picture 最小生成树

题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=1162

 

在一个二维平面坐标上有n个点,每两点之间有一条线连接,求其的最小生成树。

最基础的Kruskal算法,直接上代码。

 

代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;

/*
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
*/

int n,m;//n个点,总共有m跳边,单向边
double x[105],y[105];
int parent[105];//父亲节点
struct se
{
    int x,y;
    double w;
}edge[5055];

bool emp(se a,se b)
{
    return a.w<b.w;
}

void UFset()
{
    for(int i=0;i<=n;i++)
        parent[i]=i;
}

int find(int x)
{
    int r=x;
    while(x!=parent[x])
        x=parent[x];
    while(r!=x)//剪枝
    {
        int j=parent[r];
        parent[r]=x;
        r=j;
    }
    return x;
}

void Kruskal()
{
    int i,count=0;
    double sum=0;
    UFset();
    for(i=0;i<m;i++)
    {
        int x=edge[i].x;
        int y=edge[i].y;
        int fx=find(x),fy=find(y);
        if(fx!=fy)
        {
            count++;
            parent[fx]=fy;
            sum+=edge[i].w;
            if(count==n-1)
                break;
        }
    }
    printf("%.2f\n",sum);
}

int main()
{
    int i,j;
    while(cin>>n)
    {
        m=0;
        for(i=1;i<=n;i++)
        {
            scanf("%lf%lf",&x[i],&y[i]);
            for(j=1;j<i;j++)
            {
                edge[m].x=i;//第i个点
                edge[m].y=j;//第j个点
                edge[m].w=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));//i点和j点之间的距离
                m++;
            }
        }
        sort(edge,edge+m,emp);//边从小到大排序
        Kruskal();
    }
    return 520;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值