POJ2031 Building a Space Station(最小生成树)

kruskal求最小生成树

 

 

//poj2031 Building a Space Station
//kruskal

#include<iostream>
#include<algorithm>
#include<cstring>
#include<stdio.h>
#include<cmath>
using namespace std;

#define N 101

int     n;
int     fa[N];
double  x[N];
double  y[N];
double  z[N];
double  r[N];

struct NODE{
    int from,to;
    double length;
}node[N*N/2+1];

int find(int k){
    if(fa[k]==k) return k;
    return fa[k]=find(fa[k]);
}


bool cmp(const NODE a,const NODE b){
    return a.length<b.length;
}

double getdis(int a,int b){
    double xx=x[a]-x[b];
    double yy=y[a]-y[b];
    double zz=z[a]-z[b];
    double dis=sqrt(xx*xx+yy*yy+zz*zz);
    dis-=r[a]+r[b];
    if(dis<0) return 0;
    return dis;
}

bool judge(int point){
    int i=node[point].from;
    int j=node[point].to;
    if(find(i)!=find(j)) {
        fa[fa[i]]=fa[j];
        return 1;
    }
    return 0;
}


double kruskal(){
    for(int i=0;i<n;i++) fa[i]=i;
    int cnt=0;
    for(int i=0;i<n;i++){
        for(int j=i+1;j<n;j++){
            node[cnt].from=i;
            node[cnt].to=j;
            node[cnt++].length=getdis(i,j);
        }
    }
    sort(node,node+cnt,cmp);

    int edge=n-1;
    int point=0;
    double sum=0;
    while(edge--){
        while(!judge(point)){ point++;}
        sum+=node[point].length;
    }

    return sum;
}

int main(){
    int i,j;
    while(cin>>n&&n){
        for(i=0;i<n;i++){
            cin>>x[i]>>y[i]>>z[i]>>r[i];
        }
        printf("%.3f\n",kruskal());
    }
    return 0;
}

你可能感兴趣的:(最小生成树)