赞
踩
typedef struct closedge_node
{
VertexType adjvex;
VRType lowcost;
}closedge_node,close_edges[MAX_VERTEX_NUM];
close_edges closedge;
/** *@param G -Matrix Graph *@param s -Start point as specified *@param total_cost -Sum up the weight from minimum spanning tree *@param visit -Function pointer to print the vertex name */ void MST_Prim(MGraph G, int s, VRType *total_cost, void (*visit)(VertexType e)) { int i; int j; int k; close_edges closedge; *total_cost=0; k=LocateVex(G,G.vexs[s]); //j∈V-U, Intialize the closedge array starting from U={k} for(j=0;j<G.vexnum;j++) { if(j!=k) //j∈V-U { closedge[j].adjvex=G.vexs[s]; closedge[j].lowcost=G.arcs[k][j].adj; } } closedge[k].lowcost=0; //Move k into the U set for(i=1;i<G.vexnum;i++) { //k∈V-U k=Minimum(G,closedge); visit(closedge[k].adjvex); printf("--"); visit(G.vexs[k]); printf("\n"); *total_cost+=closedge[k].lowcost; closedge[k].lowcost=0; // j∈V-U for(j=0;j<G.vexnum;j++) { //Greedy for searching the lower cost/weight if(G.arcs[k][j].adj<closedge[j].lowcost) { closedge[j].adjvex=G.vexs[k]; closedge[j].lowcost=G.arcs[k][j].adj; } } } }
int Minimum(MGraph G, close_edges closedge) { int index; int min; int i; index=-1; min=INT_MAX; //INT_MAX defined in <limits.h> header file for(i=0;i<G.vexnum;i++) { if(closedge[i].lowcost!=0) //i∈V-U { if(min>closedge[i].lowcost) { min = closedge[i].lowcost; index=i; } } } return index; }
void visit(VertexType e); int main(void) { MGraph G; FILE *fp; int s; VRType total_cost; fp=fopen("UDN.txt","r"); s=0; total_cost=0; //Create the matrix graph on the basis of file //Reference book, <<data structure>>, Yan&Wu, TsingHua University CreateGraph(&G,fp); MST_Prim(G,s,&total_cost,visit); printf("\nThe total cost is %d\n",total_cost); PressEnter; return EXIT_SUCCESS; } void visit(VertexType e) { printf("-%c-",e); }
以上,谢谢!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。