Uva - 10397 - Connect the Campus

题意:校园里有N个点,有些点之间已有M条电缆(0 <= M <= 1000)相连,问在现有的基础上把所有的点连通最少需要多长的电缆(1 <= N <= 750)。

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=22163

——>>简单的小生成树。。。

#include <cstdio>
#include <cmath>
#include <queue>

using namespace std;

const int maxn = 750 + 10;
int N, M, fa[maxn];

struct Point{
    double x;
    double y;
}p[maxn];

double Dis(Point A, Point B){
    return sqrt((A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y));
}

struct node{
    int u;
    int v;
    double dis;
    bool operator < (const node& e) const{
        return dis > e.dis;
    }
};

void init(){
    for(int i = 1; i <= N; i++) fa[i] = i;
}

int Find(int x){
    return fa[x] == x ? x : fa[x] = Find(fa[x]);
}

bool Union(int x, int y){
    int newx = Find(x);
    int newy = Find(y);
    if(newx == newy) return 0;
    fa[newy] = newx;
    return 1;
}

void read(){
    init();
    for(int i = 1; i <= N; i++) scanf("%lf%lf", &p[i].x, &p[i].y);
    scanf("%d", &M);
    int u, v;
    for(int i = 0; i < M; i++){
        scanf("%d%d", &u, &v);
        Union(u, v);
    }
}

void Kruscal(){
    priority_queue<node> pq;
    for(int i = 1; i <= N; i++)
        for(int j = i+1; j <= N; j++)
            pq.push((node){i, j, Dis(p[i], p[j])});
    double ret = 0;
    while(!pq.empty()){
        node no = pq.top(); pq.pop();
        if(Union(no.u, no.v)) ret += no.dis;
    }
    printf("%.2f\n", ret);
}

int main()
{
    while(scanf("%d", &N) == 1){
        read();
        Kruscal();
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值