您的位置:首页 > 其它

hdu 4463 Outlets (最小生成树)

2014-11-01 21:37 295 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: