prim算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <iostream> #include <algorithm> using namespace std; #define MAX 5 #define INF 32765 int AdjMtx[MAX][MAX]= {{INF ,1,INF,4,3}, {1,INF,2,INF,INF}, {INF,2,INF,2,3}, {4,INF,2,INF,1}, {3,INF,3,1,INF}}; int lowcost[5][2]; //lowcost[][0]表示是否被选中,lowcost[][1]表示当前每个结点到选中结点的最小权值 int adjecent[MAX]; void prim( int st) { int i; for (i=0;i<MAX;i++) {lowcost[i][0]=-1;adjecent[i]=st;} //初始化时每个节点的邻接点均设为st出发点 for (i=0;i<MAX;i++) lowcost[i][1]=AdjMtx[st][i]; lowcost[st][0]=0; //表示已经被选中 int v=1; //控制结点加入个数 while (v<MAX) { int tempV,preV; //tempV存放需要加入的结点 ,tempV的前驱是preV int min=INF; for (i=0;i<MAX;i++) { if (lowcost[i][0]==-1&&lowcost[i][1]<min) { min=lowcost[i][1]; tempV=i; } } st=tempV; lowcost[st][0]=0; cout<<adjecent[st]<< "---->" <<st<< "edge added!" <<endl; for (i=0;i<MAX;i++) { if (lowcost[i][0]==-1&&AdjMtx[st][i]<lowcost[i][1]) {lowcost[i][1]=AdjMtx[st][i];adjecent[i]=st;} } v++; } } void main() { prim(3); } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步