//最小生成树 kruskal算法, 注意的是,输入的是点, 需要转换成边;
#include <iostream>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
int n, p[105];
struct Point{
double x, y;
void AddPoint(double n_x, double n_y){
x = n_x;
y = n_y;
}
}point[105];
struct Edge{
int u, v;
double w;
void AddEdge(int n_u = 0, int n_v = 0, double n_w = 0.0){
u = n_u;
v = n_v;
w = n_w;
}
}edge;
vector<Edge> ev;
bool cmp(const Edge &a, const Edge &b){
return a.w < b.w;
}
double C_weight(double x1, double y1, double x2, double y2){
return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}
void K_init(){
for(int i = 0; i <= n; ++i){
p[i] = i;
}
sort(ev.begin(), ev.end(), cmp);
}
int Find(int x){
return p[x] == x ? x : p[x] = Find(p[x]);
}
void Union(int x, int y){
int xRoot = Find(x);
int yRoot = Find(y);
p[xRoot] = yRoot;
}
double kruskal(){
K_init();
double ans = 0;
for(unsigned i = 0; i < ev.size(); ++i){
if(Find(ev[i].u) == Find(ev[i].v))
continue;
else{
Union(ev[i].u, ev[i].v);
ans += ev[i].w;
}
}
return ans;
}
int main()
{
while(scanf("%d", &n) != EOF){
double x, y;
for(int i = 0; i < n; ++i){
scanf("%lf%lf", &x, &y);
point[i].AddPoint(x, y);
}
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
if(i == j)
continue;
double w = C_weight(point[i].x, point[i].y, point[j].x, point[j].y); //计算两点之间的权值;
edge.AddEdge(i, j, w);
ev.push_back(edge);
}
}
double ans = kruskal();
printf("%.2f\n", ans);
ev.clear();
}
return 0;
}
hdu 1162
最新推荐文章于 2021-03-18 07:09:37 发布