我的思路
将所有点两两相连, 转化成线段 ,再用克鲁斯卡尔
#include<iostream>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 105;
const int maxm = 5010;
struct Point{
double x, y;
Point(double _x = 0, double _y = 0):x(_x),y(_y){}
};
struct Edge{
int v1, v2;
double weight;
Edge(int _v1 = 0, int _v2 = 0, double _weight = 0):v1(_v1),v2(_v2),weight(_weight){}
};
int n, cntp, cnte;
int parent[maxn];
int Rank[maxn];
double ans;
Point P[maxn];
Edge E[maxm];
void Init(){
ans = 0;
cntp = 0;
cnte = 0;
for(int i = 0; i < maxn; ++ i){
parent[i] = i;
Rank[i] = 1;
}
}
bool cmp(const Edge& lhs, const Edge& rhs){
return lhs.weight < rhs.weight;
}
int findRoot(int x){
int tempRoot;
int root = x;
while(root != parent[root])
root = parent[root];
while(x != root){
tempRoot = parent[x];
parent[x] = root;
x = tempRoot;
}
return root;
}
void Union(int x, int y){
int xRoot = findRoot(x);
int yRoot = findRoot(y);
if(xRoot == yRoot)
return ;
if(Rank[xRoot] < Rank[yRoot])
parent[xRoot] = yRoot;
else if(Rank[xRoot] > Rank[yRoot])
parent[yRoot] = xRoot;
else {
parent[xRoot] = parent[yRoot];
Rank[yRoot] ++;
}
}
void Kruskal(){
int edgeNum = 0;
for(int i = 0; i < cnte&& edgeNum != n - 1; ++ i){
if(findRoot(E[i].v1) == findRoot(E[i].v2))
continue;
else {
Union(E[i].v1,E[i].v2);
ans += E[i].weight;
edgeNum++;
}
}
}
int main(){
double x, y, weight;
while(scanf("%d",&n)!=EOF){
Init();
while(n--){
scanf("%lf%lf",&x, &y);
P[cntp++] = Point(x, y);
}
for(int i = 0; i < cntp; ++i){
for(int j = i + 1; j < cntp; ++j){
weight = 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));
E[cnte++] = Edge(i,j,weight);
}
}
sort(E,E+cnte,cmp);
Kruskal();
printf("%.2lf\n",ans);
}
return 0;
}