導航:首頁 > 源碼編譯 > 鄰接表的prim演算法

鄰接表的prim演算法

發布時間:2022-11-30 11:17:30

❶ C語言演算法求解:對任意給定的網路(頂點數和邊數自定),設計演算法生成它的最小生成樹。

上一個圖和代碼:

圖1為要創建的圖,圖2為對應的最小生成樹

代碼為:

//圖論之最小生成樹:prim演算法實現

#include"stdio.h"

#include"malloc.h"

//聲明

voidoutput(structadjacentlisthead*alh,intmapsize);

structadjacentlistson//鄰接表項結構體

{

intsonelement;

intquanvalue;

structadjacentlistson*next;

};

structadjacentlisthead//鄰接表頭結構體

{

charflag;

intelement;

intcurqvalue;

structadjacentlisthead*previous;

structadjacentlistson*startson;

};

structadjacentlisthead*mapinitialnize(intmapsize)//初始化圖函數

{

structadjacentlisthead*alh=NULL;

structadjacentlistson*newnode=NULL;

inti,x,y,z;

alh=malloc(sizeof(structadjacentlisthead)*mapsize);

if(alh==NULL)

returnNULL;

for(i=0;i<mapsize;i++)

{

alh[i].flag=0;

alh[i].element=i+1;

alh[i].curqvalue=0;

alh[i].previous=NULL;

alh[i].startson=NULL;

}

scanf("%d%d%d",&x,&y,&z);

while(x&&y)//直到輸入的x,y中至少有一個0為止

{

newnode=malloc(sizeof(structadjacentlistson));

newnode->sonelement=y;

newnode->quanvalue=z;

newnode->next=alh[x-1].startson;

alh[x-1].startson=newnode;

scanf("%d%d%d",&x,&y,&z);

}

returnalh;

}

intfindminnode(structadjacentlisthead*alh,intmapsize)//找到最小權值對應的結點

{

inti,minvalue=~(1<<(sizeof(int)*8-1)),minplace=0;

for(i=0;i<mapsize;i++)

{

if(alh[i].flag==0&&alh[i].curqvalue!=0)

{

if(alh[i].curqvalue<minvalue)

{

minvalue=alh[i].curqvalue;

minplace=i+1;//

}

}

}

returnminplace;

}

voidfindthemintree(structadjacentlisthead*alh,intstartplace,intmapsize)//找到最小生成樹

{

structadjacentlistson*alstmp=NULL;

intcurplace=startplace;

while(curplace)

{

alstmp=alh[curplace-1].startson;

alh[curplace-1].flag=1;//正在訪問

while(alstmp)

{

if(alh[alstmp->sonelement-1].flag==0)

{

if(alh[alstmp->sonelement-1].curqvalue==0||(alh[alstmp->sonelement-1].curqvalue>alstmp->quanvalue))//比較方法與有權圖有一點不同

{

alh[alstmp->sonelement-1].curqvalue=alstmp->quanvalue;

alh[alstmp->sonelement-1].previous=&alh[curplace-1];

}

}

alstmp=alstmp->next;

}

curplace=findminnode(alh,mapsize);//通過函數找到最小的一個結點

}

}

voidoutput(structadjacentlisthead*alh,intmapsize)

{

inti;

for(i=0;i<mapsize;i++)

{

printf("%d點的權值為:%d ",i+1,alh[i].curqvalue);

}

printf("................................................... ");

}

intmain()

{

structadjacentlisthead*alh=NULL;

intmapsize=7,startplace=1;

alh=mapinitialnize(mapsize);

findthemintree(alh,startplace,mapsize);

output(alh,mapsize);

}

輸入數據對應第一圖:

122

134

141

212

243

2510

314

342

365

411

423

432

457

468

474

5210

547

576

635

648

671

744

756

761

000

閱讀全文

與鄰接表的prim演算法相關的資料

熱點內容
管家婆輝煌2加密狗挪到另一台電腦 瀏覽:760
摩托車在哪裡app看考題 瀏覽:356
蘋果5app在哪裡設置 瀏覽:737
如何查看伺服器的磁碟使用 瀏覽:165
python蒙特卡洛模型投點圖 瀏覽:330
安卓手機屬於什麼介面 瀏覽:742
微信群推廣網站源碼 瀏覽:764
九江離鷹潭源碼 瀏覽:719
python可以當作函數的返回值 瀏覽:422
地鐵逃生體驗服怎麼進入安卓 瀏覽:833
齊魯工惠app的中獎記錄在哪裡 瀏覽:759
linuxkill命令詳解 瀏覽:103
dhcp伺服器動態分配地址 瀏覽:265
門禁卡加密了能破解嗎 瀏覽:215
在哪裡下載百度網盤app 瀏覽:917
伺服器要升級什麼意思 瀏覽:831
銀行還房貸解壓方法 瀏覽:702
伺服器主機辦公如何提速 瀏覽:920
cad列印為pdf 瀏覽:418
賣手錶的app哪裡可以賣 瀏覽:55