1、2掌握有关图的操作算法并用高级语言实现。3熟练掌握图的两种搜索路径的遍历方法。 4. 掌握图的有关应用。实验过程记录1、最小生成树 PrimKruskal算法#includestdlib.hiostream#define MAX_VERTEX_NUM 20#define OK 1#define ERROR 0#define MAX 1000using namespace std;typedef struct Arcell double adj;Arcell,AdjMatrixMAX_VERTEX_NUMMAX_VERTEX_NUM;typedef struct char vexsMAX_VER
2、TEX_NUM; /节点数组 AdjMatrix arcs; /邻接矩阵 int vexnum, arcnum; /图的当前节点数和弧数MGraph;typedef struct Pnode /用于普利姆算法 char adjvex; /节点 double lowcost; /权值Pnode,ClosedgeMAX_VERTEX_NUM; /记录顶点集U到V-U的代价最小的边的辅助数组定义typedef struct Knode /用于算法中存储一条边及其对应的2个节点 char ch1; /节点1 char ch2; /节点2 double value;/权值Knode,DgevalueMA
3、X_VERTEX_NUM;/-int CreateUDG(MGraph & G,Dgevalue & dgevalue);int LocateVex(MGraph G,char ch);int Minimum(MGraph G,Closedge closedge);void MiniSpanTree_PRIM(MGraph G,char u);void Sortdge(Dgevalue & dgevalue,MGraph G); dgevalue) /构造无向加权图的邻接矩阵 int i,j,k; coutG.vexnumG.arcnum;请输入节点: for(i=0;iG.vexnum;+i
4、)G.vexsi;+i)/初始化数组 for(j=0;j+j) G.arcsij.adj=MAX; 请输入一条边依附的定点及边的权值:endl; for(k=0;k dgevaluek.ch1 dgevaluek.ch2 dgevaluek.value; i = LocateVex(G,dgevaluek.ch1 ); j = LocateVex(G,dgevaluek.ch2 ); G.arcsij.adj = dgevaluek.value; G.arcsji.adj = G.arcsij.adj; return OK;int LocateVex(MGraph G,char ch) /确定
5、节点ch在图G.vexs中的位置 int a ; for(int i=0; i i+) if(G.vexsi = ch) a=i; return a;/typedef struct Pnode /用于普利姆算法/ char adjvex;/ double lowcost;/Pnode,ClosedgeMAX_VERTEX_NUM;void MiniSpanTree_PRIM(MGraph G,char u)/普利姆算法求最小生成树 Closedge closedge; k = LocateVex(G,u); j j+) if(j != k) closedgej.adjvex = u; clos
6、edgej.lowcost = G.arcskj.adj; closedgek.lowcost = 0; for(i=1; k = Minimum(G,closedge);(closedgek.adjvex,G.vexskclosedgek.lowcost) +j) if(G.arcskj.adj closedgej.lowcost) closedgej.adjvex = G.vexsk; closedgej.lowcost= G.arcskj.adj;int Minimum(MGraph G,Closedge closedge) /求closedge中权值最小的边,并返回其顶点在vexs中的
7、位置 int i,j; double k = 1000; if(closedgei.lowcost != 0 & closedgei.lowcost k) k = closedgei.lowcost; j = i; return j;void MiniSpanTree_KRSL(MGraph G,Dgevalue & dgevalue)/克鲁斯卡尔算法求最小生成树 int p1,p2,i,j; int bjMAX_VERTEX_NUM; /标记数组 i+) /标记数组初始化 bji=i; Sortdge(dgevalue,G);/将所有权值按从小到大排序 p1 = bjLocateVex(G,
8、dgevaluei.ch1); p2 = bjLocateVex(G,dgevaluei.ch2); if(p1 != p2)dgevaluei.ch1dgevaluei.ch2dgevaluei.value dgevaluej.value) temp = dgevaluei.value; dgevaluei.value = dgevaluej.value; dgevaluej.value = temp; ch1 = dgevaluei.ch1; dgevaluei.ch1 = dgevaluej.ch1; dgevaluej.ch1 = ch1; ch2 = dgevaluei.ch2; d
9、gevaluei.ch2 = dgevaluej.ch2; dgevaluej.ch2 = ch2;void main() MGraph G; char u; Dgevalue dgevalue; CreateUDG(G,dgevalue);图的邻接矩阵为: cout G.arcsij.adj =普利姆算法=n请输入起始点:u;构成最小代价生成树的边集为:n MiniSpanTree_PRIM(G,u);=克鲁斯科尔算法=n MiniSpanTree_KRSL(G,dgevalue);2、拓扑排序#include stdio.hconio.hstdlib.h#define STACK_INIT_SIZE 16#define STACKINCREMENT 5typedef int SElemType;typedef char VertexType; SElemType *base;SElemType *top;int stacksize;SqStack;/我们依然用邻接表来作图的存储结构typedef struct ArcNode int adjvex; struct ArcNode
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1