Prim算法

 输入事例:
7 9
1 2 28
1 6 10
2 3 16
2 7 14
3 4 12
4 5 22
4 7 18
5 6 25
5 7 24

输出:
1 6 10
6 5 25
5 4 22
4 3 12
3 2 16
2 7 14
weight if MST is 99



1
#include <cstdio> 2 #include <cstring> 3 #define INF 1000000 //无穷大 4 #define MAXN 21 //顶点个数最大值 5 6 int n, m; //顶点个数、边数 7 int Edge[MAXN][MAXN]; //邻接矩阵 8 int lowcost[MAXN]; 9 int nearvex[MAXN]; 10 11 void prim( int u0 ) //从顶点u0出发执行普里姆算法 12 { 13 int i, j; //循环变量 14 int sumweight = 0; //生成树的权值 15 16 for( i=1; i<=n; i++ ) //初始化lowcost数组和nearvex数组 17 { 18 lowcost[i] = Edge[u0][i]; 19 nearvex[i] = u0; 20 } 21 nearvex[u0] = -1; 22 23 for( i=1; i<n; i++ ) 24 { 25 int min = INF; 26 int v = -1; 27 for( j=1; j<=n; j++ ) //在lowcost数组(的nearvex[ ]值为-1的元素中)中找最小值 28 { 29 if( nearvex[j]!=-1 && lowcost[j]<min ) 30 { v = j; min = lowcost[j]; } 31 } 32 if( v!=-1 ) //v==-1,表示没找到权值最小的边 33 { 34 printf( "%d %d %d\n", nearvex[v], v, lowcost[v] ); 35 nearvex[v] = -1; 36 sumweight += lowcost[v]; 37 38 for( j=1; j<=n; j++ ) 39 { 40 if( nearvex[j]!=-1 && Edge[v][j]<lowcost[j] ) 41 { 42 lowcost[j] = Edge[v][j]; 43 nearvex[j] = v; 44 } 45 } 46 }//end of if 47 }//end of for 48 printf( "weight of MST is %d\n", sumweight ); 49 }//end of prime 50 51 int main( ) 52 { 53 int i, j; //循环变量 54 int u, v, w; //边的起点和终点及权值 55 scanf( "%d%d", &n, &m ); //读入顶点个数n和边数m 56 memset( Edge, 0, sizeof(Edge) ); 57 for( i=1; i<=m; i++ ) 58 { 59 scanf( "%d%d%d", &u, &v, &w ); //读入边的起点和终点 60 Edge[u][v] = Edge[v][u] = w; //构造邻接矩阵 61 } 62 for( i=1; i<=n; i++ ) //对邻接矩阵中其他元素值进行赋值 63 { 64 for( j=1; j<=n; j++ ) 65 { 66 if( i==j ) Edge[i][j] = 0; 67 else if( Edge[i][j]==0 ) Edge[i][j] = INF; 68 } 69 } 70 prim( 1 ); //从顶点1出发构造最小生成树 71 return 0; 72 }

 

posted @ 2014-03-04 19:40  哥的笑百度不到  阅读(173)  评论(0编辑  收藏  举报