图的--最小-连通-网

来源:互联网 发布:mysql create trigger 编辑:程序博客网 时间:2024/05/16 15:34



#include <stdio.h>#include <stdlib.h>/*------------------*time:2016-04-16*------------------*/#define VNUM 5#define MV 65536int P[VNUM];        //P[i]:the begin of Vertex,i: the end of Vertex int Cost[VNUM];     //record the Edge of weightint Mark[VNUM];     //Mark which Vertex was usedint Matrix[VNUM][VNUM] = {{0,10,15,MV,MV},{10,0,20,60,MV},{50,20,0,MV,30},{MV,60,MV,0,40},{MV,MV,30,40,0},};void Prim(int sv){if((sv>=0)&&(sv<VNUM)){int i = 0;for(i=0;i<VNUM;i++)  // provide the initial Value{P[i] = sv;Cost[i] = Matrix[sv][i];Mark[i] = 0;}Mark[sv] = 1;   //record the  begin sv Vertex to be usedint j = 0;for(i=0;i<VNUM;i++){int min = MV;int index = -1;for(j=0;j<VNUM;j++){if((!Mark[j])&&(Cost[j]<min))  //find the min weight between Edges{min = Cost[j];index = j;}}if(index > -1){Mark[index] = 1;  //record the end Vertex to be usedprintf("(%d , %d , %d)\n",P[index],index,Cost[index]);}//printf("%d\n",index);for(j=0;j<VNUM;j++)   //update the initial Value :P[] & Cost[] to find the next Vertex{if(!Mark[j] && (Matrix[index][j] < Cost[j]))//从index顶点出发,到达的顶点没有被标记, (Matrix[index][j] < Cost[j])需要好好理解,P[]和Cost[]是相互联系的 {Cost[j] = Matrix[index][j];   P[j] = index;}}}}}int main(int argc, char *argv[]) {Prim(0);return 0;}


(0 , 1 , 10)
(0 , 2 , 15)
(2 , 4 , 30)
(4 , 3 , 40)

0 0