HDU1162

我的思路

   将所有点两两相连, 转化成线段 ,再用克鲁斯卡尔

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

const int maxn = 105;
const int maxm = 5010;

struct Point{
    double x, y;
    Point(double _x = 0, double _y = 0):x(_x),y(_y){}
};

struct Edge{
    int v1, v2;
    double weight;
    Edge(int _v1 = 0, int _v2 = 0, double _weight = 0):v1(_v1),v2(_v2),weight(_weight){}
};

int n,  cntp, cnte;
int parent[maxn];
int Rank[maxn];
double ans;

Point  P[maxn];
Edge  E[maxm];

void Init(){
    ans = 0;
    cntp = 0;
    cnte = 0;
    for(int i = 0; i < maxn; ++ i){
        parent[i] = i;
        Rank[i] = 1;
    }
}

bool cmp(const Edge& lhs, const Edge& rhs){
    return lhs.weight < rhs.weight;
}


int findRoot(int x){
   int tempRoot;
   int root = x;
   while(root != parent[root])
        root = parent[root];
    while(x != root){
        tempRoot = parent[x];
        parent[x] = root;
        x = tempRoot;
    }
      return root;
}

void Union(int x, int y){
    int xRoot = findRoot(x);
    int yRoot = findRoot(y);
    
    if(xRoot == yRoot)
       return ;
    if(Rank[xRoot] < Rank[yRoot])
       parent[xRoot] = yRoot;
    else if(Rank[xRoot] > Rank[yRoot])
       parent[yRoot] = xRoot;
    else {
        parent[xRoot] = parent[yRoot];
        Rank[yRoot] ++;
    }
    
}

void Kruskal(){
    int edgeNum = 0;
    for(int i = 0; i < cnte&& edgeNum != n - 1; ++ i){
        if(findRoot(E[i].v1) == findRoot(E[i].v2))
            continue;
        else {
            Union(E[i].v1,E[i].v2);
            ans += E[i].weight;
            edgeNum++;
        }
    }
}

int main(){
    double x, y, weight;
    while(scanf("%d",&n)!=EOF){
        Init();
        while(n--){
            scanf("%lf%lf",&x, &y);
            P[cntp++] = Point(x, y);
        }
        for(int i = 0; i < cntp; ++i){
            for(int j = i + 1; j < cntp; ++j){
                weight = sqrt((P[i].x-P[j].x)*(P[i].x-P[j].x)+(P[i].y-P[j].y)*(P[i].y-P[j].y));
                E[cnte++] = Edge(i,j,weight);
            }
        }
       sort(E,E+cnte,cmp);
       Kruskal();
       printf("%.2lf\n",ans);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值