旧代码 - 最小生成树 - Prim

/*
PROG:   MST_PRIM
ID  :   ouyangyewei
LANG:   C++
*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#define DEBUG 1

const int MAXN = 1004;
const int MAXM = 15004;
const int INF = 0x3F3F3F3F;

int  N, M;
int  lowcost[MAXN], nearvex[MAXN], edge[MAXN][MAXN];

void Prim(int src)
{
    int i, j, u, minValue, sumWeight=0;
    for (i=1; i<=N; ++i)
    {
        nearvex[i]=src;
        lowcost[i]=edge[src][i];
    }// Init
    
    nearvex[src] = -1;  // firstly, only vex src is in sets
    lowcost[src]=0;
    for (i=1; i<N; ++i)
    {
        u=-1, minValue=INF;
        for (j=1; j<=N; ++j)
        {
            if ( nearvex[j]!=-1 && minValue>lowcost[j] )
                u=j, minValue=lowcost[j];
        }// Find The nearest vertex
        
        if ( u!=-1 )    // the nearest vertex has found
        {
            printf("%d %d %d\n", nearvex[u], u, lowcost[u]);

            nearvex[u] = -1;
            sumWeight += lowcost[u];
            for (j=1; j<=N; ++j)
            {
                if ( nearvex[j]!=-1 && edge[u][j]<lowcost[j] )
                    nearvex[j]=u, lowcost[j]=edge[u][j];
            }
        }// End of if
    }// Main Process
    
    printf("lowcost is : %d\n", sumWeight);
}// Prim

int main()
{
#if DEBUG
    freopen("E:\\MST.txt", "r", stdin);
    freopen("E:\\MST_Prim.txt", "w", stdout);
#endif

    int i, u, v, w;
    while (~scanf("%d %d", &N, &M), N+M!=0)
    {
        memset(edge, INF, sizeof(edge));
        
        for (i=1; i<=M; ++i)
        {
            scanf("%d %d %d", &u, &v, &w);
            edge[u][v] = edge[v][u] = w;
        }// creat the graph
        
        Prim( 1 );  // 0 for start point
    }// End of while
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值