poj3625

注意要用double型读入否则精度有问题/* * poj3625.cpp * * Created on: 2010-8-18 * Author: friendy */

/*
 * poj3625.cpp
 *
 *  Created on: 2010-8-18
 *      Author: friendy
 */

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

struct Edge{
	int s,t;
	double dis;
	bool operator<(const Edge &other)const{
		return dis<other.dis;
	}
}edge[1000001];
double sum=0;
double point[1001][2];
int map[1001][1001];
int f[1001],rank[1001],n;
void Init(){
	int i;
	for(i=1;i<=n;i++){
		f[i]=i;
		rank[i]=0;
	}
}

int Find(int x){
	if(x!=f[x])
		f[x]=Find(f[x]);
	return f[x];
}

void Union(int i,int j,int k){
	int x=Find(i);
	int y=Find(j);
	if(x==y)
		return ;
	sum+=sqrt((double)edge[k].dis);
	if(rank[x]>rank[y])
		f[y]=x;
	else
	{
		f[x]=y;
		if(rank[x]==rank[y])
			rank[y]++;
	}
}
int main(){
	int i,j,m,num,a,b;
	scanf("%d%d",&n,&m);
	for(i=1;i<=n;i++){
		scanf("%lf %lf",&point[i][0],&point[i][1]);
	}
	Init();
	memset(map,0,sizeof(map));
	for(i=0;i<m;i++){
		scanf("%d%d",&a,&b);
		map[a][b]=map[b][a]=1;
	}
	num=0;
	for(i=1;i<=n-1;i++){
		for(j=i+1;j<=n;j++){
			if(map[i][j]){
				edge[num].s=i;
				edge[num].t=j;
				edge[num].dis=0.0;
				num++;
			}
			else{
				edge[num].s=i;
				edge[num].t=j;
				edge[num].dis=(point[i][0]-point[j][0])*(point[i][0]-point[j][0])+(point[i][1]-point[j][1])*(point[i][1]-point[j][1]);
				num++;
			}
		}
	}
	sort(edge,edge+num);

	for(i=0;i<num;i++){
		Union(edge[i].s,edge[i].t,i);
	}
	printf("%.2f\n",sum);
}


 

你可能感兴趣的:(poj3625)