洛谷 1991 无线通讯网 kruskal

本文通过一道具体的题目,介绍了如何使用Kruskal算法解决最小生成树问题。文章详细阐述了算法的具体实现过程,并展示了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一本正经的刷水题,,

传送门

题解:

题目给定了卫星的数量,也就是说,最后整张图形成的联通块的数量要小于等于该数,手动连边,kruskal加边,满足条件时输出当前边并且exit

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#define y1 ajksch
struct edge{
    int from;
    int to;
    double val;
};

const int maxn = 800000;
int s, p;
edge t[maxn];
int x1[maxn], y1[maxn];
int father[1000];
int tot = 0;
int getfather(int x) {
    if (father[x] == x) return (x);
    return (father[x] = getfather(father[x]));
}
bool cmp(edge aa, edge bb) {
    return (aa.val < bb.val);
}
int main () {
    scanf("%d %d", &s, &p);
    for (int i = 1; i <= p; i++) {
        scanf("%d %d", &x1[i], &y1[i]);
        for (int j = 1; j < i; j++) {
            tot++;
            t[tot].from = i;
            t[tot].to = j;
            t[tot].val = (x1[i] - x1[j]) * (x1[i] - x1[j]) + (y1[i] - y1[j]) * (y1[i] - y1[j]);
        }
    }
    std :: sort(t + 1, t + tot + 1, cmp);
    for (int i = 1; i <= p; i++) father[i] = i;
    int cur = p;
    for (int i = 1; i <= tot; i++) {
        int tx = getfather(t[i].from);
        int ty = getfather(t[i].to);
        if (tx == ty) continue;
        cur--;
        if (cur == s) {
            printf("%.2lf", sqrt(t[i].val));
            exit(0);
        }
        father[tx] = ty;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值