最小生成树板子
虽然不知道我写的那一版为什么错
需要注意的是,递归调用层数过多,也会显示内存超限
ti
#include<bits/stdc++.h>
using namespace std;
struct Node{
double x, y;
};
struct opop{
int xx, yy;
double dd;
bool operator <(const opop &t) const{
return dd < t.dd;
}
};
vector<Node>no;
vector<opop>oop;
int h[101];
int f[101];
bool op[101];
void init(int n){
for(int i = 0; i <= n; i ++ ){
f[i] = i;
h[i] = 0;
}
oop.clear();
no.clear();
return ;
}
int find(int x){
if(x != f[x]){
f[x] = find(f(x));
}
return f[x];
}
int main()
{
int n;
while(cin>>n){
init(n);
Node q;
opop p;
for(int i = 0; i < n; i ++ ){
cin>>q.x>>q.y;
no.push_back(q);
}
for(int i = 0; i < no.size() - 1; i ++ ){
for(int j = i + 1; j < no.size(); j ++ ){
double l = sqrt((no[i].x - no[j].x) * (no[i].x - no[j].x) + (no[i].y - no[j].y) * (no[i].y - no[j].y)); //计算任意两点间距离
p.xx = i, p.yy = j, p.dd = l;
oop.push_back(p);
}
}
sort(oop.begin(), oop.end());
double ans = 0; //记录最小生成树边长
for(int i = 0; i < oop.size(); i ++ ){
int xt = find(oop[i].xx);
int yt = find(oop[i].yy);
double d = oop[i].dd;
if(f[xt] != f[yt]){
ans += d;
if(h[xt] > h[yt]){
f[yt] = xt;
}
else if(h[yt] > h[xt]){
f[xt] = yt;
}
else {
f[xt] = yt;
h[yt] ++ ;
}
}
}
printf("%.2f", ans);
}
return 0;
}