0718-最小生成树-洛谷2847 奶牛广播

本文介绍了一种使用Prim算法结合堆优化解决最小生成树问题的方法,以帮助奶牛们找到最小花费使通信网络强连通。

https://www.luogu.org/problemnew/show/P2847

题目描述

(英文的直接忽略)

FJ的N头牛(1≤N≤1000)为了在他们之间传播信息, 想要组织一个"哞哞广播"系统. 奶牛们决定去用步话机装备自己而不是在很远的距离之外互相哞哞叫, 所以每一头奶牛都必须有一个步话机. 这些步话机都有一个限制传播半径, 但是奶牛们可以间接地通过中间奶牛传播信息, 所以并不是每头牛都必须直接向其他每一头奶牛连边.

奶牛们需要去决定多少钱花在步话机上, 如果他们花了$X, 那么他们都将会得到sqrt(x)距离的步话机. 所以, 两头牛之间的欧几里得距离最多是X. 请帮助奶牛们找到最小的X使得图是强连通的.、

输入输出格式

输入格式:

The first line of input contains N .

The next N lines each contain the xx and yy coordinates of a single cow. These are both integers in the range 0 \ldots 25,0000…25,000 .

输出格式:

Write a single line of output containing the integer XX giving the minimum amount the cows must spend on walkie-talkies.

输入输出样例

输入样例#1: 

4
1 3
5 4
7 2
6 1

输出样例#1: 

17

说明

感谢@MrMorning 提供翻译

这是一道很裸的最小生成树,应该用Prim和Kruskal都可以,毕竟数据不大

但我用的是Prim,再加上了一点堆优化(其实和Dijkstra很类似)

直接上代码

#include <map>
#include <cstring>
#include <iostream>
#include<vector>
#include<cstdio>
#include<cmath>
#include<algorithm> 
#include<queue>
#define inf 0x3f3f3f3f 
using namespace std;
long long mapp[1009][1009];
struct node1{
    int x,y;
}a[1009];
struct node{
    int id;
    long long dis;
};
bool operator < (node a,node b){
//重载运算符,使得大根堆变小根堆,为什么不直接压入负数(?备注1)
    return a.dis>b.dis;
}
priority_queue<node>  q;
int n;
long long Distance(node1 a,node1 b){//这个地方小心,别写distance
    return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
bool vst[1009];
int main()
{
    scanf("%d",&n);
    int i,j,k,u,v;
    for(i=1;i<=n;++i){
        scanf("%d%d",&a[i].x,&a[i].y);
    }
    memset(mapp,inf,sizeof(mapp));
    for(i=1;i<=n;++i)
        for(j=1;j<=n;++j){
            
            if(i!=j) {
                mapp[i][j]=mapp[j][i]=Distance(a[i],a[j]);
            }
        }
    memset(vst,0,sizeof(vst)); 
    q.push((node){1,0});//强制转化为node类型,压入
    long long maxn=-1;
    while(!q.empty()){
        node temp=q.top();
        q.pop();
        if(vst[temp.id]) continue;
        vst[temp.id]=1;
        maxn=max(maxn,temp.dis);//因为最后根据题意只需要最大的那一边
        for(i=1;i<=n;++i)
        {
            if(vst[i]) continue;
            q.push((node){i,mapp[i][temp.id]});
//因为是小根堆,所以不用多加判断,全部都压进去,反正最后只会top()出最小的
        }
    }
    printf("%lld",maxn);
    return 0;
}

备注:

1.因为这个大根堆是node类型的,如果你不重载运算符,那判断的时候就会出问题

但如果是int的话,就可以直接压入负数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值