YTU 1012 : A MST Problem

题目描述

It is just a mining spanning tree ( 最小生成树 ) problem, what makes you a little difficult is that you are in a 3D space.

输入

The first line of the input contains the number of test cases in the file. And the 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

contains Three Integer Numbers xi,yi and zi, indicating the position of point i.

输出

For each test case, output a line with the answer, which should accurately rounded to two decimals .
样例输入
2
2
1 1 0
2 2 0
3
1 2 3
0 0 0
1 1 1

样例输出
1.41
3.97

今天做一道炒鸡难的生成树题目到现在还没有思路,很烦~刚好学校oj上有道生成树的入门级题目,先刷为敬。
题目的意思就是在一个三维空间给出几个点让我们求最小生成数的路径和(翻译过来还不说输出啥,试了试对了),Kruskal算法比较好实现,这里就只给出prim算法的解吧。
AC代码如下:

#include <iostream>
#include <stdio.h>
//#define sf scanf
//#define pf printf
using namespace std;
#include <cmath>
#include <cstring>
#define INF 32767

double ma1p[40][40];
double minv[40];
int vis[40];
int n,m;
typedef struct 
{
    int x,y,z;
}D3;
D3 a[40];

void prim(int x)
{
    int u;
    double minwei;
    double ans = 0;
    for(int j = 1;j <= n;j++)
        minv[j] = ma1p[x][j];
    vis[x] = 1;
    for(int i = 2;i <= n;i++)
    {
        minwei = INF;
        for(int j = 1;j <= n;j++)
        {
            if(minwei > minv[j] && !vis[j])
            {
                minwei = minv[j];
                u = j;
            }
        }
        vis[u] = 1;
        ans += minv[u];
        for(int j = 1;j <= n;j++)
            if(!vis[j] && minv[j] > ma1p[u][j])
            minv[j] = ma1p[u][j];
    }
    //pf("%.2f\n",ans);
    printf("%.2f\n",ans);
}

int main()
{
    cin>>m;
    while(m--)
    {
        cin>>n;
        for(int i = 1; i<= n;i++)
            for(int j = 1;j <= n;j++)
            ma1p[i][j] = INF;
        for(int i = 1;i <= n;i++)
            scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);
        double wei;
        for(int i = 1;i <= n;i++)
            for(int j = i + 1; j <= n;j++)
            {
                wei = sqrt((a[i].x - a[j].x)*(a[i].x - a[j].x)+(a[i].y - a[j].y)*(a[i].y - a[j].y) + (a[i].z - a[j].z)*(a[i].z - a[j].z));
                ma1p[i][j] = ma1p[j][i] = wei;
            }
        memset(vis,0,sizeof vis);
        prim(1);
    }
}

另,原本想整理一下A和IDA,但是发现自己的水平不足以分析清楚,所以这两个算法在寒假结束前找时间整理吧。
文中有不妥之处,望各位大佬指出。

猜你喜欢

转载自blog.csdn.net/qm230825/article/details/86532879
MST