|
发表于 2023-2-25 16:20:23
|
显示全部楼层
- #include <stdio.h>
- #include <stdlib.h>
- #define MAXVEX 32 // 最大顶点数
- #define INFINITY 65535 // 用65535来代表无穷大
- /*6 8
- 1 2 7
- 2 4 1
- 4 5 4
- 2 5 2
- 1 5 3
- 1 6 8
- 1 3 2
- 3 6 9*/
- int pt[MAXVEX];
- typedef struct line
- {
- int x,y,w ;
- struct line *next;
- }line;
- typedef struct headNode
- {
- int pt[MAXVEX],havpt[MAXVEX];
- line ln[MAXVEX],*tree[MAXVEX];
- int ptnum,lnnum;
- }headNode;
- void create(headNode* hd)
- {
- scanf("%d%d",&(hd->ptnum),&(hd->lnnum));
- line* ln=hd->ln,*p=hd->ln;
- for(int i=1;i<=hd->lnnum;i+=1)
- {
- scanf("%d%d%d",&ln[i].x,&ln[i].y,&ln[i].w);
- p=ln;
- while(p->next&&p->next->w<ln[i].w)p=p->next;
- ln[i].next=p->next;
- p->next=&ln[i];
- }
- p=ln;
- while(p->next)
- {
- printf("%d--%d %d\n",p->next->x,p->next->y,p->next->w);
- p=p->next;
- }
- }
- // 建立邻接表
- //Prim算法生成最小生成树
- int MiniSpanTree(headNode *hd) {
- int *pt=hd->pt,*hpt=hd->havpt,ct=0,i,min,j;
- line* ln=hd->ln,*p=NULL,*ptmp;
- pt[1]=1;
- hpt[1]=1;
- ct=1;
- j=0;
- while(ct<hd->ptnum)
- {
- min=INFINITY;
- for(i=1,ptmp=NULL,pt[0]=0;pt[i];i+=1)
- {
- p=ln;
- while(p->next)
- {
- j+=1;
- if(pt[i]==p->next->x||pt[i]==p->next->y)
- {
- if(hpt[p->next->x]&&hpt[p->next->y])
- {
- p->next=p->next->next;
- continue;
- }
- else if((min>p->next->w)&&(hpt[p->next->x]||hpt[p->next->y]))
- {
- min=p->next->w;
- if(hpt[p->next->x])pt[0]=p->next->y;
- else pt[0]=p->next->x;
- ptmp=p;
- break;
- }
- }
- p=p->next;
- }
- }
- if(ptmp->next)
- {
- hd->tree[ct++]=ptmp->next;
- pt[ct]=pt[0];
- hpt[pt[0]]=1;
- ptmp->next=ptmp->next->next;
- }
- }
- return 0;
- }
- int main()
- {
- headNode head={0};
- create(&head);
- MiniSpanTree(&head);
- for(int i=1;head.tree[i];i+=1)
- printf("%d--%d\n",head.tree[i]->x,head.tree[i]->y);
- return 0;
- }
复制代码 |
|