洛谷P2872题解

我们假设图G是完全图,预先计算好所有边的权值并加入边集。

for(int i = 1; i<=N; ++i)
        for(int j = i+1; j<=N; ++j){
            edge[++cnt].x = i;
            edge[cnt].y = j;
            edge[cnt].w = cal_dis(i, j);
        }

在读入输入数据已给的M条边时,直接进行并查集合并处理。

 for(int i = 1; i<=M; ++i){
        int x, y;
        scanf("%d %d", &x, &y);
        int fx = find(x);
        int fy = find(y);
        fa[fx] = fy;
    }

再此基础上再跑一遍Kruskal算法,用贪心策略选边使整个图连通即可。以下是全部代码:

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

#define MaxN 1005
#define MaxM 1005

struct NODE{
    double x, y;
}node[MaxN];

struct EDGE{
    int x, y;
    double w;
}edge[MaxN*MaxN];
int cnt;
double ans;

bool cmp(EDGE a, EDGE b){
    return a.w<b.w;
}

int N, M;
int fa[MaxN];

double cal_dis(int x, int y){
    double tmp =  (double)(node[x].x-node[y].x)*(node[x].x-node[y].x);
    tmp += (double)(node[x].y-node[y].y)*(node[x].y-node[y].y);
    tmp = sqrt((double)tmp);
    return tmp;
}

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

int main(){
    scanf("%d %d", &N, &M);
    for(int i = 1; i<=N; ++i) fa[i] = i;
    for(int i = 1; i<=N; ++i) scanf("%lf %lf", &node[i].x, &node[i].y);
    for(int i = 1; i<=N; ++i)
        for(int j = i+1; j<=N; ++j){
            edge[++cnt].x = i;
            edge[cnt].y = j;
            edge[cnt].w = cal_dis(i, j);
        }
    sort(edge+1, edge+1+cnt, cmp);
    for(int i = 1; i<=M; ++i){
        int x, y;
        scanf("%d %d", &x, &y);
        int fx = find(x);
        int fy = find(y);
        fa[fx] = fy;
    }
    for(int i = 1; i<=cnt; ++i){
        int fx = find(edge[i].x);
        int fy = find(edge[i].y);
        if(fx == fy) continue;
        ans += edge[i].w;
        ++M;
        fa[fx] = fy;
    }
    printf("%.2lf\n", ans);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值