P2872 [USACO07DEC] Building Roads S
题目描述
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.
给定 nnn 个点的坐标,第 iii 个点的坐标为 (xi,yi)(x_i,y_i)(xi,yi),这 nnn 个点编号为 111 到 nnn。给定 mmm 条边,第 iii 条边连接第 uiu_iui 个点和第 viv_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,mn,mn,m 代表点数与边数。
接下来 nnn 行每行两个整数 xi,yix_i,y_ixi,yi 代表第 iii 个点的坐标。
接下来 mmm 行每行两个整数 ui,viu_i,v_iui,vi 代表第 iii 条边连接第 uiu_iui 个点和第 viv_ivi 个点。
输出格式
* 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.
一行一个实数代表添加的边的最小长度,要求保留两位小数,为了避免误差, 请用 646464 位实型变量进行计算。
输入输出样例 #1
输入 #1
4 1
1 1
3 1
2 3
4 3
1 4
输出 #1
4.00
说明/提示
数据规模与约定
对于 100%100\%100% 的整数,1≤n,m≤10001 \le n,m \le 10001≤n,m≤1000,1≤xi,yi≤1061 \le x_i,y_i \le 10^61≤xi,yi≤106,1≤ui,vi≤n1 \le u_i,v_i \le n1≤ui,vi≤n。
说明
Translated by 一只书虫仔。
C++实现
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int x[1000001],y[1000001],b[1001],lj[10001],n,m,k,sum,h,l;
double a[1001][1001],d[10001],tot;
double js(int x1,int x2,int y1,int y2){
return sqrt(pow(double(x1-x2),2)+pow(double(y1-y2),2));
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>x[i]>>y[i];
for(int i=1;i<=n-1;i++)
for(int j=i+1;j<=n;j++) {
a[i][j]=a[j][i]=js(x[i],x[j],y[i],y[j]);
}
for(int i=1;i<=m;i++) {
cin>>h>>l;
a[h][l]=a[l][h]=0;
}
memset(d,0x7f,sizeof(d));
for(int i=1;i<=n;i++) {
d[i]=a[1][i];
}
d[1]=0;
b[1]=1;
for(int i=1;i<=n-1;i++) {
k=0;
for(int j=1;j<=n;j++)
if(!b[j]&&d[j]<d[k])
k=j;
b[k]=1;
for(int j=1;j<=n;j++)
if(!b[j]&&a[j][k]<d[j])
d[j]=a[j][k];
}
for(int i=1;i<=n;i++) {
tot+=d[i];
}
printf("%.2lf",tot);
}

后续
接下来我会不断用C++来实现信奥比赛中的算法题、GESP考级编程题实现、白名单赛事考题实现,记录日常的编程生活、比赛心得,感兴趣的请关注,我后续将继续分享相关内容
用C++实现信奥 P2872 USACO07DEC Building Roads S&spm=1001.2101.3001.5002&articleId=147752115&d=1&t=3&u=8e131b00de53402e866cde80df3690cf)
395

被折叠的 条评论
为什么被折叠?



