最小生成树 Freckles

链接:点击打开链接


大意就是给你几个点让你用最短的线把他们连起来,最小生成树,权重自己算

prim?不存在的,我就是喜欢kruskal,膨胀.jpg微笑

(所以这就是我现在还不会prim的理由咯)

#include<cstdio>  
#include<cstring>  
#include<cmath>  
#include<algorithm>  
using namespace std;
#define N 105  
double coord[N][2], w[N][N];
int n, pos;
int f[N*N];
 
struct Edge {
    int u, v;
    double val;
    friend bool operator<(const Edge&a, const Edge&b) {
        return a.val < b.val;
    }
}arr[N*N];
 
inline double getDist(double x1, double y1, double x2, double y2) {
    return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}
 
void init() {
    for (int i = 0; i < N*N; ++i)
        f[i] = i;
}
int find(int x) {
    int i, j = x;
    if (j != f[j]) f[j]=find(f[j]);
    //while (x != j) { i = f[x]; f[x] = j; x = i; }
    return f[j];
}
bool Union(int x, int y) {
    int a = find(x), b = find(y);
    if (a == b)return false;
     
    else f[a] = b;
     
    return true;
}
 
int main() {
     
        scanf("%d", &n);
        for (int i = 1; i <= n; ++i)
            scanf("%lf%lf", &coord[i][0], &coord[i][1]);
 
        pos = 0;
        for (int i = 1; i <= n; ++i) {
            for (int j = i + 1; j <= n; ++j) {
                arr[pos].u = i, arr[pos].v = j;
                arr[pos++].val = getDist(coord[i][0], coord[i][1],
                    coord[j][0], coord[j][1]);
            }
        }
        double ans = 0;
        init();
        sort(arr, arr + pos);
        for (int i = 0; i<pos; ++i) {
            if (Union(arr[i].u, arr[i].v))
                ans += arr[i].val;
        }
        printf("%.2f\n", ans);
     
     
    return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值