poj 2031 Building a Space Station

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

三维最小生成树

 1 #include<iostream>

 2 #include<cmath>

 3 #include<string>

 4 #include<algorithm>

 5 #include<queue>

 6 #include<cstring>

 7 #include<cstdio>

 8 

 9 using namespace std;

10 

11 const int N=105;

12 struct node

13 {

14     double x,y,z;

15     double r;

16 }mem[N];

17 double dist[N][N];

18 double finddist(int i,int j)

19 {

20     double dt=sqrt((mem[i].x-mem[j].x)*(mem[i].x-mem[j].x)

21                 +(mem[i].y-mem[j].y)*(mem[i].y-mem[j].y)

22                    +(mem[i].z-mem[j].z)*(mem[i].z-mem[j].z));

23     //cout<<mem[i].x<<" "<<mem[j].x<<endl;

24     //cout<<dt<<endl;

25     dt=dt-mem[i].r-mem[j].r;

26     if(dt<0.0)

27     dt=0.0;

28     //cout<<i<<" "<<j<<" "<<dt<<endl;

29     return dt;

30 }

31 int main()

32 {

33     int n;

34     while(scanf("%d",&n)!=EOF,n)

35     {

36         for(int i=1;i<=n;++i)

37         {

38             scanf("%lf %lf %lf %lf",&mem[i].x,&mem[i].y,&mem[i].z,&mem[i].r);

39             for(int j=1;j<i;++j)

40             {

41                 dist[i][j]=dist[j][i]=finddist(i,j);

42             }

43         }

44             double ans=0.0;

45             bool had[N];

46             memset(had,false,sizeof(had));

47             had[1]=true;

48             for(int w=1;w<n;++w)

49             {

50                 double Min=200000.0;

51                 int k=0;

52                 for(int i=1;i<=n;++i)

53                 {

54                     if(had[i])

55                     {

56                        for(int j=2;j<=n;++j)

57                        {

58                            if(!had[j]&&dist[i][j]<Min)

59                            {

60                                Min=dist[i][j];

61                                k=j;

62                            }

63                        }

64                     }

65                 }

66                 ans=ans+Min;

67                 had[k]=true;

68             }

69             printf("%.3f\n",ans);

70     }

71     return 0;

72 }

 

你可能感兴趣的:(Build)