蓝桥杯-通电(并查集)

蓝桥杯-通电

https://www.lanqiao.cn/problems/162/learning/

解题思路

将所有路径算出来存进结构体Edge dc[i]中,然后开始求最短路径
PS:
1-并查集最小数
2-计算公式有误,正确公式为sqrt(pow(x1-x2,2)+pow(y1-y2,2))+pow(h1-h2,2);

#include <bits/stdc++.h>
using namespace std;

struct Node
{
    int x,y,h;
} ct[1010];

struct Edge
{
    int x,y;
    double h;
    bool operator <(const Edge&z)
    {
        return h<z.h;
    }
} dc[500100];

double ans;
int bk[1010];

int getf(int i)
{
    if(i==bk[i])
        return i;
    return bk[i]=getf(bk[i]);
}
void mer(int i)
{
    int f1=getf(dc[i].x),f2=getf(dc[i].y);//寻找源头
    if(f1==f2)//若源头相同则已是最优解,不需要合并
        return;
    bk[f2]=f1;//合并数
    ans+=dc[i].h;//计和
    return ;
}
double fun(int i,int j)
{
    double px=pow(ct[i].x-ct[j].x,2);
    double py=pow(ct[i].y-ct[j].y,2);
    double ph=pow(ct[i].h-ct[j].h,2);
    return sqrt(px+py)+ph;
}
int main()
{
    int n,k;
    cin>>n;

    for(int i=1; i<=n; i++)
    {
        cin>>ct[i].x>>ct[i].y>>ct[i].h;
        bk[i]=i;//所有村庄是自己的源头
    }
    k=1;
    for(int i=1; i<=n; i++)
    {
        for(int j=i+1; j<=n; j++,k++)
        {//将所有路径算出来存进结构体Egde dc[i]中
            dc[k].x=i;
            dc[k].y=j;
            dc[k].h=fun(i,j);
        }
    }
    sort(dc+1,dc+k);//结构体排序
    for(int i=1; i<k; i++)
    {//建树
        mer(i);
    }
    printf("%.2lf",ans);
    // cout<<ans<<endl;
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ja Vas Kokhaju

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值