hdu1233

题解:

  Prim算法。因为该图为完全图,用邻接矩阵存储。注意所开数组的大小及判断条件。

代码如下:

#include <stdio.h>
#define MaxVex 110

int MGraph[MaxVex][MaxVex];
typedef struct Closedge
{
    int adjvex;
    int lowcost;
}closedge[MaxVex];

int minimum(closedge &ce, int n)
{
    int i = 1, k, min;
    while (!ce[i].lowcost)//辅助数组中第1个非零数
        i++;
    min = ce[i].lowcost;
    k = i;
    for (; i<=n; i++)
    {//找出辅助数组中的最小值(除零外)
        if (ce[i].lowcost)
        {
            if (ce[i].lowcost < min)
            {
                k = i;
                min = ce[k].lowcost;
            }
        }
    }
    return k;//返回辅助数组的非零最小值的下标
}

int main()
{//Prim算法:
    int k, i, j, n, m, sum;
    closedge ce;
    while (scanf("%d", &n) && n)
    {
        for (k=1; k<=n*(n-1)/2; k++)
        {//邻接矩阵初始化
            scanf("%d%d%d", &i, &j, &m);
            MGraph[i][j] = MGraph[j][i] = m;
        }
        k = 1;//从1开始构造最小生成树
        for (j=1; j<=n; j++)
        {//辅助数组初始化
            if (k != j)
            {
                ce[j].adjvex = k;
                ce[j].lowcost = MGraph[k][j];
            }
        }
        sum = ce[k].lowcost = 0; //初始:U = {u}, sum;
        for (i=1; i<n; i++)
        {//选择其余n-1个顶点
            k = minimum(ce, n);
            sum += ce[k].lowcost;
            ce[k].lowcost = 0;//第k个顶点并入U集
            for (j=1; j<=n; j++)
            {//更新辅助数组
                if (MGraph[k][j] < ce[j].lowcost)
                {
                    ce[j].adjvex = j;
                    ce[j].lowcost = MGraph[k][j];
                }
            }
        }
        printf("%d\n", sum);
    }
    return 0;
}

 

posted on 2013-02-07 13:39  zm001  阅读(222)  评论(0编辑  收藏  举报