hdu 4463 Outlets (最小生成树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4463

裸的最小生成树,算是签到题了。~~

code:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

const int maxe=10100;
const int maxn=100;

struct edge
{
    int u,v;
    double cost;
} P[maxe];

struct pos
{
    int x,y;
} pp[maxn];

int par[maxn];
int high[maxn];

void init(int n)
{
    for(int i=0;i<=n;i++){
        par[i]=i;
        high[i]=0;
    }
}

int Find(int x)
{
    if(par[x]==x) return x;
    else return par[x]=Find(par[x]);
}

void unite(int x,int y)
{
    x=Find(x);
    y=Find(y);
    if(x==y) return ;
    if(high[x]<high[y]){
        par[x]=y;
    }
    else{
        par[y]=x;
        if(high[x]==high[y]) high[x]++;
    }
}

bool same(int x,int y)
{
    return Find(x)==Find(y);
}

bool cmp(const edge &e1,const edge &e2)
{
    return e1.cost<e2.cost;
}

int V,E,p,q;

double kruskal()
{
    init(V);
    double res;
    p--;
    q--;
    res=sqrt((double)(pp[p].x-pp[q].x)*(pp[p].x-pp[q].x)+(double)(pp[p].y-pp[q].y)*(pp[p].y-pp[q].y));
    unite(p,q);
    sort(P,P+E,cmp);
    for(int i=0;i<E;i++){
        edge e=P[i];
        if(!same(e.u,e.v)){
            unite(e.u,e.v);
            res+=e.cost;
        }
    }
    return res;
}

int main()
{
    while(scanf("%d",&V),V!=0){
        E=0;
        scanf("%d%d",&p,&q);
        for(int i=0;i<V;i++){
            scanf("%d%d",&pp[i].x,&pp[i].y);
        }
        for(int i=0;i<V;i++){
            for(int j=i+1;j<V;j++){
                P[E].u=i;
                P[E].v=j;
                P[E++].cost=sqrt((double)(pp[i].x-pp[j].x)*(pp[i].x-pp[j].x)+(double)(pp[i].y-pp[j].y)*(pp[i].y-pp[j].y));
            }
        }
        printf("%.2f\n",kruskal());
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值