题目链接
无坑,AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 105;
const int inf = 0x3f3f3f3f;
struct point{
int x, y;
point(){
}
point(int xx, int yy){
x = xx;
y = yy;
}
};
struct edge{
int u, v;
double w;
edge(){
}
edge(int uu, int vv, double ww){
u = uu, v = vv, w = ww;
}
bool operator < (const edge a) const{
return w > a.w;
}
};
priority_queue<edge>que;
vector<point>arr;
int n, cnt, fa[maxn];
double ans;
void init(){
cnt = n;
ans = 0;
for(int i = 1; i <= n; i++)
fa[i] = i;
}
int getf(int a){
if(a == fa[a])
return a;
return fa[a] = getf(fa[a]);
}
bool sam(int a, int b){
if(getf(a) == getf(b))
return true;
return false;
}
void merge(int a, int b){
if(sam(a, b))
return ;
fa[getf(a)] = getf(b);
}
double dis(point a, point b){
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
int main(){
cin>>n;
init();
for(int i = 0; i < n; i++){
point temp;
scanf("%d%d", &temp.x, &temp.y);
arr.push_back(temp);
for(int j = 0; j < arr.size(); j++)
que.push(edge(i, j, dis(arr[i], arr[j])));
}
while(cnt != 1){
edge temp = que.top();
que.pop();
if(!sam(temp.u, temp.v)){
merge(temp.u, temp.v);
cnt--;
ans += temp.w;
}
}
printf("%.2f\n", ans);
return 0;
}