YTU 1012: A MST Problem
发布时间:2021年12月06日 20:10:40
发布人:jqh?
**Description**
It is just a mining spanning tree ( 最小生成树 ) problem, what makes you a little difficult is that you are in a 3D space.
**Input**
The first line of the input contains the number of test cases in the file. And t he first line of each case
contains one integer numbers n(0<n<30) specifying the number of the point . The n next n line s, each line
contain s Three Integer Numbers xi,yi and zi, indicating the position of point i.
Output
For each test case, output a line with the answer, which should accurately rounded to two decimals .
```cpp
#include <iostream>
#include <cstdio>
#include <cmath>
#include <memory.h>
using namespace std;
struct node
{
  int x,y,z;
}vertex[30];
int main()
{
  int te,n;
  double graph[30][30],cost[30];
  bool s[30];
  cin>>te;
  for(int ti=0;ti<te;++ti)
  {
     double ans=0;
     cin>>n;
     memset(s,false,sizeof(s));
     for(int i=0;i<n;++i)
        cin>>vertex[i].x>>vertex[i].y>>vertex[i].z;
     for(int i=0;i<n;++i)//求每两个点之间的边的长度
        for(int j=0;j<n;++j)
           graph[i][j]=sqrt((vertex[i].x-vertex[j].x)
       *(vertex[i].x-vertex[j].x)+(vertex[i].y-vertex[j].y)
       *(vertex[i].y-vertex[j].y)+(vertex[i].z-vertex[j].z)
       *(vertex[i].z-vertex[j].z));
       //prim算法求最小生成树
     s[0]=true;
     for(int i=1;i<n;++i)
        cost[i]=graph[0][i];
     for(int i=1;i<n;++i)
     {
        double min_cost=0xffff;
      int min_index;
        for(int j=0;j<n;++j)
           if(!s[j]&&cost[j]<min_cost)
        min_cost=cost[j],min_index=j;
      s[min_index]=true;
      ans+=min_cost;
      for(int j=0;j<n;++j)
         if(!s[j]&&cost[j]>graph[min_index][j])
          cost[j]=graph[min_index][j];
     }
     printf("%.2lf\n",ans);
  }
  return 0;
}
```
			
热门评论: