题目描述
题目描述
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.
给定 n 个点的坐标,第 i 个点的坐标为 (x_i,y_i),这 n 个点编号为 1 到 n。给定 m 条边,第 i条边连接第 u_i个点和第 v_i个点。现在要求你添加一些边,并且能使得任意一点都可以连通其他所有点。求添加的边的总长度的最小值。
输入格式
* 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行每行两个整数 x_i,y_i 代表第 i 个点的坐标。
接下来 m行每行两个整数 u_i,v_i代表第 i条边连接第 u_i个点和第 v_i 个点。
输出格式
* 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 位实型变量进行计算。
样例
输入样例:
4 1
1 1
3 1
2 3
4 3
1 4
输出样例:
4.00
算法1
(Kruskal)
C++ 代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
typedef double d;
int n,m,cnt;
d x[N],y[N];
int f[N];
struct Edge
{
int a,b;
d w;
}edges[N];
bool cmp(Edge a,Edge b)
{
return a.w<b.w;
}
d dis(d x1,d y1,d x2, d y2)
{
d xx=x1-x2,yy=y1-y2;
return xx*xx+yy*yy;
}
int find(int x)
{
return f[x]==x?x:f[x]=find(f[x]);
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>x[i]>>y[i];
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<i;j++)
{
cnt++;
edges[cnt]={i,j,dis(x[i],y[i],x[j],y[j])};
}
}
for(int i=1;i<=m;i++)//依题意在此多做一些处理,因为Kruskal算法是按边权从小到大排序,所以这里只需要加入一条新的边权为0的边.
{
int u,v;
cin>>u>>v;
cnt++;
edges[cnt]={u,v,0.0};
}
sort(edges+1,edges+cnt+1,cmp);
for(int i=1;i<=n;i++) f[i]=i;
d res=0;
for(int i=1;i<=cnt;i++)
{
int f1=find(edges[i].a),f2=find(edges[i].b);
if(f1!=f2)
{
f[f1]=f2;
res+=sqrt(edges[i].w);
}
}
printf("%.2lf\n",res);
return 0;
}