标签:
Description
Input
Output
Sample Input
3 10.000 10.000 50.000 10.000 40.000 10.000 50.000 10.000 40.000 40.000 50.000 10.000 2 30.000 30.000 30.000 20.000 40.000 40.000 40.000 20.000 5 5.729 15.143 3.996 25.837 6.013 14.372 4.818 10.671 80.115 63.292 84.477 15.120 64.095 80.924 70.029 14.881 39.472 85.116 71.369 5.553 0
Sample Output
20.000 0.000 73.834
这道题是MST水题,只是把点换成3维坐标的形式。
上代码:
#include<iostream>
#include<cstring>
#include<cmath>
#include<iomanip>
using namespace std;
const int MAXN=105;
const double INF=99999999.9;
struct Point
{
double x,y,z,r;
}point[MAXN];
double lowc[MAXN];
bool vis[MAXN];
double cost[MAXN][MAXN];
double get_dis(int i,int j)
{
return sqrt((point[i].x-point[j].x)*(point[i].x-point[j].x)+(point[i].y-point[j].y)*(point[i].y-point[j].y)+
(point[i].z-point[j].z)*(point[i].z-point[j].z));
}
double prim(int n) //我就是因为这里把double写成了int,结果wa了一次,细心,真的很重要啊。
{
memset(vis,false,sizeof(vis));
double ans=0.0;
vis[0]=true;
for(int i=1;i<n;i++)
lowc[i]=cost[0][i];
for(int i=1;i<n;i++)
{
double minc=INF;
int p=-1;
for(int j=0;j<n;j++)
if(!vis[j]&&lowc[j]<minc)
{
minc=lowc[j];
p=j;
}
if(minc==INF)
return -1;
ans+=minc;
vis[p]=true;
for(int j=0;j<n;j++)
if(!vis[j]&&cost[p][j]<lowc[j])
lowc[j]=cost[p][j];
}
return ans;
}
int main()
{
int n;
while(cin>>n)
{
if(n==0)
break;
for(int i=0;i<n;i++)
{
cin>>point[i].x>>point[i].y>>point[i].z>>point[i].r;
}
double dis;
for(int i=0;i<n;i++)
{
lowc[i]=INF;
for(int j=0;j<n;j++)
{
dis=get_dis(i,j)-point[i].r-point[j].r;
if(dis<=0.000)
cost[i][j]=cost[j][i]=0.0;
else
cost[i][j]=cost[j][i]=dis; //无向图
}
}
double ans=prim(n);
cout<<setiosflags(ios::fixed)<<setprecision(3)<<ans<<endl;
}
return 0;
}
poj_2301_Building a Space Station_mst
标签:
原文地址:http://www.cnblogs.com/-maybe/p/4247700.html