题目描述
Farmer John had just acquired several new farms! He wants to connect the farms with roads so that he can travel from any farm to any other farm via a sequence of roads; roads already connect some of the farms.
Each of the N (1 ≤ N ≤ 1,000) farms (conveniently numbered 1..N) is represented by a position (Xi, Yi) on the plane (0 ≤ Xi ≤ 1,000,000; 0 ≤ Yi ≤ 1,000,000). Given the preexisting M roads (1 ≤ M ≤ 1,000) as pairs of connected farms, help Farmer John determine the smallest length of additional roads he must build to connect all his farms.
给定 nn 个点的坐标,第 ii 个点的坐标为 (x_i,y_i)(xi,yi),这 nn 个点编号为 11 到 nn。给定 mm 条边,第 ii 条边连接第 u_iui 个点和第 v_ivi 个点。现在要求你添加一些边,并且能使得任意一点都可以连通其他所有点。求添加的边的总长度的最小值。
输入格式
* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: Two space-separated integers: Xi and Yi
* Lines N+2..N+M+2: Two space-separated integers: i and j, indicating that there is already a road connecting the farm i and farm j.
第一行两个整数 n,m 代表点数与边数。
接下来 n 行每行两个整数 xi,yi 代表第 i 个点的坐标。
接下来 m 行每行两个整数 ui,vi 代表第 i 条边连接第 ui 个点和第 vi 个点。
输出格式
* Line 1: Smallest length of additional roads required to connect all farms, printed without rounding to two decimal places. Be sure to calculate distances as 64-bit floating point numbers.
一行一个实数代表添加的边的最小长度,要求保留两位小数,为了避免误差, 请用 64 位实型变量进行计算。
输入输出样例
输入 #1
4 1
1 1
3 1
2 3
4 3
1 4
输出 #1
4.00
说明/提示
数据规模与约定
对于 100% 的整数,1≤n,m≤1000,1≤xi,yi≤10^6,1≤ui,vi≤n。
坑:关于距离公式:
sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}
但是必须要控制精度,否则#2 #8 #9 #10会挂掉!
将这个:
tree[num].data=sqrt((room[i].x-room[j].x)*(room[i].x-room[j].x)+(room[i].y-room[j].y)*(room[i].y-room[j].y));
改成这个:
tree[num].data=sqrt((double)(room[i].x-room[j].x)*(room[i].x-room[j].x)+(double)(room[i].y-room[j].y)*(room[i].y-room[j].y));
然后就AC了!!!!!
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
struct node{
int from,to;
double data;
}tree[10000000];
struct position{
int x,y;
}room[10000];
int vis[10000];
int father(int x){
if(x==vis[x]){
return x;
}
return vis[x]=father(vis[x]);
}
void link(int x,int y){
vis[father(x)]=father(y);
}
bool cmp(node a,node b){
return a.data<b.data;
}
int main(){
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d%d",&room[i].x,&room[i].y);
}
int num=0;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
tree[num].from=i;
tree[num].to=j;
tree[num].data=sqrt((double)(room[i].x-room[j].x)*(room[i].x-room[j].x)+(double)(room[i].y-room[j].y)*(room[i].y-room[j].y));
//cout<<tree[num].data<<endl;
num++;
}
}
sort(tree,tree+num,cmp);
for(int i=1;i<=n;i++){
vis[i]=i;
}
int it=m;
for(int i=1;i<=m;i++){
int x,y;
scanf("%d%d",&x,&y);
link(x,y);
}
double sum=0;
for(int i=0;i<num;i++){
if(father(tree[i].from)!=father(tree[i].to)){
link(tree[i].from,tree[i].to);
sum+=tree[i].data;
it++;
}
if(it==n-1) break;
}
printf("%.2lf\n",sum);
}