旧代码 - 最小生成树 - Prim

来源:互联网 发布:c语言鸡兔同笼循环 编辑:程序博客网 时间:2024/06/08 16:32
/*PROG:   MST_PRIMID  :   ouyangyeweiLANG:   C++*/#include <stdio.h>#include <stdlib.h>#include <memory.h>#define DEBUG 1const 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);}// Primint 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;}

原创粉丝点击