/*
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;
}
旧代码 - 最小生成树 - Prim
最新推荐文章于 2018-09-28 00:19:16 发布