//zjscs.cpp--minimum cost spanning tree
#include < limits.h >
#include < stdio.h >
#include < stdlib.h >
#include "myconst.h"
#define MAX_VERTEX_NUM 20
#define INFINITY INT_MAX
typedef int VRType;
typedef int VertexType;
typedef struct ArcCell {
VRType adj;
}
ArcCell,
AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct {
VertexType vexs[MAX_VERTEX_NUM];
AdjMatrix arcs;
int vexnum,
arcnum;
}
MGraph;
typedef struct {
VertexType adjvex;
VRType lowcost;
}
close;
Status CreateUDN(MGraph & G);
int LocateVex(const MGraph & G, VertexType v);
Status PrintVex(const MGraph & G, int i);
int minimum(const MGraph & G, close closedge[]);
void MiniSpanTree(const MGraph & G, VertexType u);
int main(void) {
MGraph G;
printf("\n");
CreateUDN(G);
MiniSpanTree(G, G.vexs[0]);
return 0;
}
void MiniSpanTree(const MGraph & G, VertexType u) {
int i,
j,
k;
close closedge[MAX_VERTEX_NUM];
k = LocateVex(G, u);
for (j = 0; j < G.vexnum; j++) if (j != k) {
closedge[j].adjvex = u;
closedge[j].lowcost = G.arcs[k][j].adj;
}
closedge[k].lowcost = 0;
for (i = 1; i < G.vexnum; i++) {
k = minimum(G, closedge);
printf("zxscs bian:%5d%5d\n", closedge[k].adjvex, G.vexs[k]);
closedge[k].lowcost = 0;
for (j = 0; j < G.vexnum; j++) if (G.arcs[k][j].adj < closedge[j].lowcost) {
closedge[j].adjvex = G.vexs[k];
closedge[j].lowcost = G.arcs[k][j].adj;
}
}
}
Status CreateUDN(MGraph & G) {
int i,
j,
k;
VertexType v1,
v2;
VRType w;
printf("Enter vertex number:");
scanf("%d", &G.vexnum);
printf("Enter arc number:");
scanf("%d", &G.arcnum);
for (i = 0; i < G.vexnum; i++) {
printf("Enter %d vertex:", i + 1);
scanf("%d", &G.vexs);
}
for (i = 0; i < G.vexnum; i++) for (j = 0; j < G.vexnum; j++) G.arcs[j].adj = INFINITY;
for (k = 0; k < G.arcnum; k++) {
printf("Enter %d arc:\n", k + 1);
printf("Enter the first vertex:");
scanf("%d", &v1);
printf("Enter the second vertex:");
scanf("%d", &v2);
printf("Enter the w:");
scanf("%d", &w);
i = LocateVex(G, v1);
j = LocateVex(G, v2);
G.arcs[j].adj = G.arcs[j].adj = w;
}
return OK;
}
int LocateVex(const MGraph & G, VertexType v) {
int i = 0;
while (G.vexs != v) i++;
if (i < G.vexnum) return i;
else return INFEASIBLE;
}
int minimum(const MGraph & G, close closedge[]) {
int i,
j,
k;
for (i = 0; i < G.vexnum; i++) if (closedge.lowcost) break;
k = i;
for (j = i + 1; j < G.vexnum; j++) if (closedge[j].lowcost && closedge[j].lowcost < closedge[k].lowcost) k = j;
return k;
}
Status PrintVex(const MGraph & G, int i) {
printf("%5d", G.vexs);
return OK;
}
zxscs
最新推荐文章于 2020-09-20 13:28:57 发布