完善代码:#include <stdio.h> #include <stdlib.h> #define INF 50 typedef struct ArcNode{ int adjvex;//该弧所指向的顶点位置 struct ArcNode *nextarc;//下一个临接点 int weight;//弧的权重 }ArcNode;//表结点 typedef struct VNode{ char data; //顶点信息 ArcNode *firstarc;//指向下一个结点. }VNode,AdjList[6]; typedef struct{ AdjList LH;//创建头结点数组 int vexnum;//图的点的个数 int arcnum;//图的边的个数 }Graph; typedef struct{ char nextvex; int lowcost; int know; }Auxiliary_array;//辅助数组结构体 voidmain (void){ void buildtu (Graph*); void printgraph(Graph*); void prim( Graph *G, char u); char u; Graph UDG; Graph *G = &UDG; buildtu(G); printgraph(G);//打印图 printf("请输入起始顶点: \n"); while(getchar()!=')n'); u = getchar(); prim(G,u); } void buildtu (Graph*G) { //建图 int search(Graph *G,char a); int i,n1,n2,w;char a,b; ArcNode *p, *q; printf("请输入顶点个数和边的条数: \n"); scanf("%d %d",&G->vexnum,&G->arcnum); printf("请输入顶点信息\n"); for (i= 0;i< G->vexnum; ++i){ while (getchar()!='\n'); scanf("%c" ,&G->LH[i].data); G->LH[i].firstarc = NULL; } printf(" 请输入有关系的结点和该边的权重:\n");for(i=0;i<G->arcnum;++i){ while (getchar()!='\n'); scanf("%c %c %d",&a,&b,&w); n1=search(G,a); n2=search(G,b); p=G->LH[n1].firstarc; if(p == NULL){ p=G->LH[n1].firstarc=(ArcNode *) malloc (sizeof(ArcNode)); } else{ while(p->nextarc!=NULL){ p=p->nextarc; } p=p->nextarc=(ArcNode*)malloc(sizeof(ArcNode)); }
时间: 2024-03-19 22:42:35 浏览: 114
p->adjvex=n2;//弧指向的结点位置
p->weight=w;//弧的权重
p->nextarc=NULL;//下一个临接点为空
q=G->LH[n2].firstarc;
if(q == NULL){
q=G->LH[n2].firstarc=(ArcNode *) malloc (sizeof(ArcNode));
}
else{
while(q->nextarc!=NULL){
q=q->nextarc;
}
q=q->nextarc=(ArcNode*)malloc(sizeof(ArcNode));
}
q->adjvex=n1;//弧指向的结点位置
q->weight=w;//弧的权重
q->nextarc=NULL;//下一个临接点为空
}
}
int search(Graph *G,char a){//查找结点位置
int i;
for(i=0;i<G->vexnum;++i){
if(G->LH[i].data==a){
return i;
}
}
return -1;
}
void printgraph(Graph*G){//打印图
int i;
ArcNode *p;
printf("图的邻接表为:\n");
for(i=0;i<G->vexnum;++i){
printf("%c -> ",G->LH[i].data);
p=G->LH[i].firstarc;
while(p!=NULL){
printf("%c(%d) ",G->LH[p->adjvex].data,p->weight);
p=p->nextarc;
}
printf("\n");
}
}
void prim( Graph *G, char u){//prim算法
int i,j,k;
Auxiliary_array *D;
ArcNode *p;
int min;
k=search(G,u);
D=(Auxiliary_array*)malloc(sizeof(Auxiliary_array)*G->vexnum);
for(i=0;i<G->vexnum;++i){
if(i!=k){
D[i].nextvex=u;
D[i].lowcost=INF;
D[i].know=0;
}
}
p=G->LH[k].firstarc;
while(p!=NULL){
i=p->adjvex;
D[i].nextvex=u;
D[i].lowcost=p->weight;
D[i].know=1;
p=p->nextarc;
}
D[k].know=1;
D[k].lowcost=0;
for(i=1;i<G->vexnum;++i){
min=INF;
for(j=0;j<G->vexnum;++j){
if(D[j].know==0 && D[j].lowcost<min){
min=D[j].lowcost;
k=j;
}
}
D[k].know=1;
p=G->LH[k].firstarc;
while(p!=NULL){
j=p->adjvex;
if(D[j].know==0 && p->weight<D[j].lowcost){
D[j].lowcost=p->weight;
D[j].nextvex=G->LH[k].data;
}
p=p->nextarc;
}
}
printf("最小生成树为:\n");
for(i=0;i<G->vexnum;++i){
if(i!=k){
printf("(%c,%c)\n",D[i].nextvex,G->LH[i].data);
}
}
}
阅读全文