最小生成树(邻接表写法)
#include<stdio.h> #include<stdlib.h> #define max 20 typedef struct ArcNode { int adjvex; struct ArcNode *nextarc; int info; } ArcNode; typedef struct VertexNode { char data; ArcNode *firstarc; }VertexNode; typedef struct{ VertexNode vertex[max]; int vexnum,arcnum; }AdjList; AdjList *G=(AdjList *)malloc(sizeof(AdjList)); AdjList *primtree=(AdjList *)malloc(sizeof(AdjList)); int locatevertex(AdjList *G,char x) { for(int i=0;i<G->vexnum;i++) { if(G->vertex[i].data==x) return i; } return -1; } int creategraph(AdjList *G) /*建立一张图*/ { int i,j,k,power; char v1,v2; printf("请输入顶点数和边数: "); scanf("%d%d",&G->vexnum,&G->arcnum); fflush(stdin); printf("请输入顶点: "); for(i=0;i<G->vexnum;i++) { fflush(stdin); scanf("%c",&G->vertex[i].data); G->vertex[i].firstarc=NULL; } printf("请输入边和权值: "); for(i=0;i<G->arcnum;i++) { fflush(stdin); scanf("%c %c%d",&v1,&v2,&power); j=locatevertex(G,v1); k=locatevertex(G,v2); ArcNode *arc=(ArcNode *)malloc(sizeof(ArcNode)); arc->adjvex=k; arc->info=power; arc->nextarc=G->vertex[j].firstarc; G->vertex[j].firstarc=arc; arc=(ArcNode *)malloc(sizeof(ArcNode)); arc->adjvex=j; arc->info=power; arc->nextarc=G->vertex[k].firstarc; G->vertex[k].firstarc=arc; } } void initprimtree(AdjList *G,AdjList *primtree) /*初始化最小生成树*/ { int i; for(i=0;i<G->vexnum;i++) { primtree->vertex[i].data=G->vertex[i].data; primtree->vertex[i].firstarc=NULL; } primtree->vexnum=G->vexnum; } ArcNode *makenode(int adjvex,int power) /*建立新结点*/ { ArcNode *newnode=(ArcNode *)malloc(sizeof(ArcNode)); newnode->nextarc=NULL; newnode->adjvex=adjvex; newnode->info=power; return newnode; } void createprimtree(AdjList *G,AdjList *primtree) /*生成最小生成树*/ { int visit[G->vexnum]; /*visit记录是否访问过该顶点*/ int i,j,k; int power,adjvex; ArcNode *temp=(ArcNode *)malloc(sizeof(ArcNode)); for(i=0;i<G->vexnum;i++) /*visit置为0,表示顶点都还未访问*/ visit[i]=0; visit[0]=1; /*访问第一个顶点*/ for(i=0;i<G->vexnum;i++) { power=999; for(j=0;j<G->vexnum;j++) { if(visit[j]) /*如果该顶点访问过,寻找和该顶点相邻的最小权值的未被访问的顶点*/ { temp=G->vertex[j].firstarc; while(temp!=NULL) { if(power>temp->info&&!visit[temp->adjvex]) /*找到和该顶点相邻的最小权值的未被访问的顶点更新信息*/ { power=temp->info; adjvex=temp->adjvex; k=j; /*保存两个邻接的权值最小的顶点信息*/ } temp=temp->nextarc; } } } if(!visit[adjvex]) { if(primtree->vertex[k].firstarc==NULL) primtree->vertex[k].firstarc=makenode(adjvex,power); /*将未访问的顶点接在已访问的顶点的后面*/ else { temp=primtree->vertex[k].firstarc; while(temp->nextarc!=NULL) temp=temp->nextarc; temp->nextarc=makenode(adjvex,power); } visit[adjvex]=1; } } } void print(AdjList *primtree) /*打印最小生成树*/ { ArcNode *p; p=(ArcNode *)malloc(sizeof(ArcNode)); int i; for(i=0;i<primtree->vexnum;i++) { p=primtree->vertex[i].firstarc; while(p) { printf("%c—%c(%d) ",primtree->vertex[i].data,primtree->vertex[p->adjvex].data,p->info); p=p->nextarc; } } } int main() { creategraph(G); /*建立一张图*/ initprimtree(G,primtree); /*初始化最小生成树*/ createprimtree(G,primtree); /*生成最小生成树*/ printf("最小生成树为: "); print(primtree); /*打印最小生成树*/ return 0; }
下一篇:
如何判断单向链表有环?