1. 程式人生 > >POJ 2031

POJ 2031

最小生成樹水題

程式碼:

#include<iostream>
#include<cmath>
#include<iomanip>
#include<cstring>
using namespace std;
const double inf=100000;
int n;
double x[200],y[200],z[200],r[200],map[200][200];
int flag[200];
void prim(){
   int i,j,pos;
   double low[200],minn,sum=0;
   memset(flag,0,sizeof(flag));
   //cout<<n<<endl;
   for(i=2;i<=n;i++){low[i]=map[1][i];}
   for(i=2;i<=n;i++)
   {
    minn=inf;
   // cout<<flag[2]<<flag[3]<<endl;
    for(j=2;j<=n;j++)
    if(!flag[j]&&low[j]<minn){pos=j;minn=low[j];}
    flag[pos]=1;
   // cout<<low[2]<<" "<<low[3]<<endl;
    sum+=minn;
    for(j=2;j<=n;j++)
    if(!flag[j]&&map[pos][j]<low[j])low[j]=map[pos][j];
   }
   cout<<fixed<<setprecision(3)<<sum<<endl;
}
int main(){
   int i,j;
   double t;
   while(cin>>n&&n)
   {
    for(i=1;i<=n;i++)cin>>x[i]>>y[i]>>z[i]>>r[i];
    for(i=1;i<=n;i++)
    for(j=1;j<=n;j++)
    {
     t=(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])+(z[i]-z[j])*(z[i]-z[j]);
     if(t>(r[i]+r[j])*(r[i]+r[j]))map[i][j]=sqrt(t)-r[i]-r[j];
     else map[i][j]=0;
     //cout<<map[i][j]<<endl;
    }
    prim();
   }
   return 0;
}