poj2031 kruskal

来源:互联网 发布:淘宝上新怎么抢的快 编辑:程序博客网 时间:2024/04/28 17:34

http://poj.org/problem?id=2031

#include<iostream>#include<algorithm>#include<cmath>#include<cstdio>using namespace std;double a[101][4];double esp = 0.0000001;struct edge{    int u,v;    double w;} e[5000];int tree[101];int cmp( const void *a ,const void *b){    return (*(edge *)a).w > (*(edge *)b).w ? 1 : -1 ;}int main(){    int n;    //freopen("1.txt","r",stdin);    while (cin>>n,n)    {        int i,j;        for (i = 0; i < n; ++i)            cin >> a[i][0] >> a[i][1] >> a[i][2] >> a[i][3];        int k = 0;        for (i = 0; i < n-1; ++i)            for (j = i+1; j < n; ++j)            {                e[k].u = i;                e[k].v = j;                double temp = sqrt( (a[i][0]-a[j][0])*(a[i][0]-a[j][0])                                    +(a[i][1]-a[j][1])*(a[i][1]-a[j][1])                                    +(a[i][2]-a[j][2])*(a[i][2]-a[j][2]) )- a[i][3] - a[j][3];                if (temp < esp)                    e[k].w = 0;                else                    e[k].w = temp;                ++k;            }        qsort(e,k,sizeof(e[0]),cmp);        for (i = 0; i < n; ++i)            tree[i] = i;        double total = 0;        for (i = 0; i < k; ++i)        {            int m1 = tree[e[i].u];            int m2 = tree[e[i].v];            if (m1 != m2)            {                total += e[i].w;                for (j = 0; j < n; ++j)                    if (tree[j] == m2)                        tree[j] = m1;            }        }        printf("%.3f\n",total);    }    return 0;}

  

原创粉丝点击