题目的意思就是给出有几个建筑物的,然后是这几个建筑物的坐标.
在给出已经联通的建筑物有哪些.
问建筑全部联通还需要多长的边.
就是用并查集,但是其中几个点设置组成已联通.
AC代码:
#include<stdio.h>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 1005 ;
struct point {
double x;
double y;
}p[N];
int f[N];
double sum;
double w[N];
int s[N * N];
int l[N];
int r[N];
int num;
int find(int x) {
return f[x] == x ? x : find(f[x]);
}
int cmp (int x , int y) {
return w[x] < w[y];
}
int main() {
int n,m;
int a,b;
while(~scanf("%d",&n)) {
for (int i = 1 ; i <= n ;i++) {
scanf("%lf%lf",&p[i].x ,&p[i].y);
}
for (int i = 0 ; i < n ;i++) {
f[i] = i;
}
sum = 0 ;
scanf("%d",&m);
for (int i = 0 ; i < m ;i++) {
scanf("%d%d",&a,&b);
f[find(a)] = find(b);
}
num = 0;
for (int i = 1 ; i < n ;i++) {
for (int j = i + 1 ;j < n ;j++) {
w[num] = sqrt( (p[i].x - p[j].x ) * (p[i].x - p[j].x) + (p[i].y - p[j].y) * (p[i].y -p[j].y) ) ;
l[num] = i ;
r[num] = j ;
num++;
}
}
for (int i = 0; i < num;i++) {
s[i] = i;
}
sort(s , s + num ,cmp);
for (int i = 0 ; i < num ;i++) {
int e = s[i];
int x = find(l[e]);
int y = find(r[e]);
if (x != y) {
sum += w[e] ;
f[x] = y;
}
}
printf("%.2lf\n",sum);
}
}