#include<cstdlib> #include<cstdio> #include<cstring> #define MAXVEX 100 #define INFINITY 65535 typedef struct { char vexs[MAXVEX]; int arc[MAXVEX][MAXVEX]; int numVextexes,numEdges; }MGraph; void CreateGraph(MGraph *G){ int i,j,k,w; printf("输入顶点数和边数:\n"); scanf("%d %d",&G->numVextexes,&G->numEdges); for(i=0;i<G->numVextexes;i++){ scanf(&G->vexs[i]); } for(i=0;i<G->numVextexes;i++){ for(j=0;j<G->numVextexes;j++){ G->arc[i][j] = INFINITY; } } printf(" G->numEdges = %d \n",G->numEdges); for(k=0;k<G->numEdges;k++){ // printf(" k = %d \n",k); printf("输入边(Vi,Vj)上的下标1,和下标j和权w:\n"); scanf("%d %d %d",&i,&j,&w); G->arc[j][i] = G->arc[i][j] = w; } return; } void MiniSpanTree_Prim(MGraph G){ int min,i,j,k,p; int adjvex[MAXVEX]; //保存相关顶点下标 int lowcost[MAXVEX]; //==========这个自己亲自多跑跑代码就懂了,不要懵,不要乱就能得出规律和结论 lowcost[0] = 0; adjvex[0] = 0; for(i=1;i<G.numVextexes;i++){ lowcost[i] = G.arc[0][i]; adjvex[i] = 0; } for(i=1;i<G.numVextexes;i++){ min = INFINITY; j = 1;k = 0; // for(p=0;p<G.numVextexes;p++) printf("%d ",adjvex[p]); while(j<G.numVextexes){ if(lowcost[j] != 0 && lowcost[j] < min){ min = lowcost[j]; k = j; } j++; } // for(p=0;p<G.numVextexes;p++) printf("%d ",lowcost[p]); printf("\n(%d,%d)\n",adjvex[k],k); lowcost[k] = 0; for(j = 0;j< G.numVextexes;j++){ if(lowcost[j]!=0 && G.arc[k][j] < lowcost[j]){ lowcost[j] = G.arc[k][j]; adjvex[j] = k; } } } return; } int main(){ MGraph G; CreateGraph(&G); MiniSpanTree_Prim(G); return 0; }