資料結構(C實現)------- 最小產生樹之Prim演算法,-------prim

來源:互聯網
上載者:User

資料結構(C實現)------- 最小產生樹之Prim演算法,-------prim

[本文是自己學習所做筆記,歡迎轉載,但請註明出處:http://blog.csdn.net/jesson20121020]

演算法描述

  如果連通圖是一個網,則稱該網中所有產生樹中權值總和最小的產生樹為最小產生樹,也稱最小代價產生樹。利用Prim演算法構造的最小產生樹方法思想:

  假設G=(V,E)是一個具有n個頂點的連通網,頂點集V={v1,v2,...,vn}.設所求的最小產生樹T=(U,TE),其中U是T的頂點集,TE是T的邊集,U和TE初值均為空白集。

  Prim演算法的基本思想如下:首先從V中任取一個頂點(假定取v1),將產生樹T置為僅有一個結點v1的樹,即U={v1};然後只要U是V的真子集,就在所有那些一個端點在T中,另一個端點在T外的邊中,找一條最短(即權值最小 )的邊。假定合格最短邊為(vi,vj),則把該條邊和其不在T中的頂點vj,分別併入T的邊集TE和頂點集U。如此進行下去,每次往產生樹裡併入一個頂點和一條邊,直到把所有頂點都包括進產生樹T為止。此時,必有U=V,TE中有n-1條邊,則T=(U,TE)是G的一棵最小產生樹。

演算法實現

  設一個edge數組,記錄從頂點U集到V-U的代價最小的邊,每條邊的資訊包括邊的始點和,終點和權值。從頂點u出發,利用prim演算法求最小產生樹步驟如下:

  (1) 初始化edge數組,記錄頂點u到圖中其餘結點的代價最小的n-1的邊。

  (2) 將頂點u加入U中。

  (3) 當U不等於V時,做如下處理。

    1) 從edge數組中選一條代價最小的邊。

    2) 將該邊的終點加入U中。

    3) 調整edges數組,使它始終記錄頂點U到V-U的代價最小的邊。

演算法代碼

// 定義邊結構體typedef struct{int start;int end;int cost;}Edge;/*  *Prim演算法求最小產生樹 * */void Prim_MG(MGraph MG,char vs){Edge edge[MAX_VEX_NUM];int i,j,k,v,min;int s = getIndexOfVexs(vs,&MG);//初始化邊for(i = 1;i <= MG.vexnum;i++){if(s != i){edge[i].start = s;edge[i].end = i;edge[i].cost = MG.arcs[s][i];}}//首先將s加入產生樹集合中edge[s].cost = 0;for(i = 2;i <= MG.vexnum;i++){min = 1000;for(j = 1;j<= MG.vexnum;j++){if(edge[j].cost != 0 && edge[j].cost < min ){min = edge[j].cost;k = j;}}v = edge[k].end;edge[v].cost = 0; // 加入新節點//輸出產生樹中的邊 printf("%c %c %d\n",MG.vexs[edge[v].start],MG.vexs[edge[v].end],MG.arcs[edge[v].start][edge[v].end]);//重新調整數組for(j = 1;j <= MG.vexnum;j++){if(edge[j].cost != 0 && MG.arcs[v][j] != 0 && MG.arcs[v][j] < edge[j].cost){edge[j].start = k;edge[j].end = j;edge[j].cost = MG.arcs[v][j];}}}}

演算法說明

  假設圖中有n個頂點,則第一個進行初始化的迴圈語句的頻度為n,第二個迴圈語句頻度為n-1。其中有兩個內迴圈;其一是在edge數組中找權值最小的邊,其頻度為n-1,其二是重新調整edge數組的邊,頻度為n,所以Prim演算法的時間複雜度為O(n^2),而與圖中的邊數無關,因此適用於求稠密的最小產生樹。


完整代碼

/* * ===================================================================================== * *       Filename:  Prim.c * *    Description:  最小產生樹演算法之Prim演算法  * *        Version:  1.0 *        Created:  2015年03月11日 15時27分19秒 *       Revision:  none *       Compiler:  gcc * *         Author:  jesson20121020 (), 997287955@qq.com *   Organization:   * * ===================================================================================== */#include <stdio.h>#include <stdlib.h>#define MAX_VEX_NUM 50#define UN_REACH 1000typedef char VertexType;typedef enum {DG, UDG} GraphType;typedef struct {VertexType vexs[MAX_VEX_NUM];int arcs[MAX_VEX_NUM][MAX_VEX_NUM];int vexnum, arcnum;GraphType type;} MGraph;/** * 根據名稱得到指定頂點在頂點集合中的下標 * vex  頂點 * return 如果找到,則返回下標,否則,返回0 */int getIndexOfVexs(char vex, MGraph *MG) {int i;for (i = 1; i <= MG->vexnum; i++) {if (MG->vexs[i] == vex) {return i;}}return 0;}/** * 建立鄰接矩陣 */void create_MG(MGraph *MG) {int i, j, k,weight;int v1, v2, type;char c1, c2;printf("Please input graph type DG(0) or UDG(1) :");scanf("%d", &type);if (type == 0)MG->type = DG;else if (type == 1)MG->type = UDG;else {printf("Please input correct graph type DG(0) or UDG(1)!");return;}printf("Please input vexmun : ");scanf("%d", &MG->vexnum);printf("Please input arcnum : ");scanf("%d", &MG->arcnum);getchar();for (i = 1; i <= MG->vexnum; i++) {printf("Please input %dth vex(char):", i);scanf("%c", &MG->vexs[i]);getchar();}//初始化鄰接矩陣for (i = 1; i <= MG->vexnum; i++) {for (j = 1; j <= MG->vexnum; j++) {if(i == j)MG->arcs[i][j] = 0;elseMG->arcs[i][j] = UN_REACH;}}//輸入邊的資訊,建立鄰接矩陣for (k = 1; k <= MG->arcnum; k++) {printf("Please input %dth arc v1(char) v2(char) weight(int): ", k);scanf("%c %c %d", &c1, &c2,&weight);v1 = getIndexOfVexs(c1, MG);v2 = getIndexOfVexs(c2, MG);if (MG->type == 1)MG->arcs[v1][v2] = MG->arcs[v2][v1] = weight;elseMG->arcs[v1][v2] = weight;getchar();}}/** * 列印鄰接矩陣和頂點資訊 */void print_MG(MGraph MG) {int i, j;if(MG.type == DG){printf("Graph type: Direct graph\n");}else{printf("Graph type: Undirect graph\n");}printf("Graph vertex number: %d\n",MG.vexnum);printf("Graph arc number: %d\n",MG.arcnum);printf("Vertex set:\n ");for (i = 1; i <= MG.vexnum; i++)printf("%c\t", MG.vexs[i]);printf("\nAdjacency Matrix:\n");for (i = 1; i <= MG.vexnum; i++) {j = 1;for (; j < MG.vexnum; j++) {printf("%d\t", MG.arcs[i][j]);}printf("%d\n", MG.arcs[i][j]);}}// 定義邊結構體typedef struct{int start;int end;int cost;}Edge;/*  *Prim演算法求最小產生樹 * */void Prim_MG(MGraph MG,char vs){Edge edge[MAX_VEX_NUM];int i,j,k,v,min;int s = getIndexOfVexs(vs,&MG);//初始化邊for(i = 1;i <= MG.vexnum;i++){if(s != i){edge[i].start = s;edge[i].end = i;edge[i].cost = MG.arcs[s][i];}}//首先將s加入產生樹集合中edge[s].cost = 0;for(i = 2;i <= MG.vexnum;i++){min = 1000;for(j = 1;j<= MG.vexnum;j++){if(edge[j].cost != 0 && edge[j].cost < min ){min = edge[j].cost;k = j;}}v = edge[k].end;edge[v].cost = 0; // 加入新節點//輸出產生樹中的邊 printf("%c %c %d\n",MG.vexs[edge[v].start],MG.vexs[edge[v].end],MG.arcs[edge[v].start][edge[v].end]);//重新調整數組for(j = 1;j <= MG.vexnum;j++){if(edge[j].cost != 0 && MG.arcs[v][j] != 0 && MG.arcs[v][j] < edge[j].cost){edge[j].start = k;edge[j].end = j;edge[j].cost = MG.arcs[v][j];}}}}/** * 主函數 */int main(void) {MGraph MG;char startVex;create_MG(&MG);print_MG(MG);printf("\nPlease input the start vex(char):");scanf("%c",&startVex);printf("\nThe result of Prim:\n");Prim_MG(MG,startVex);return EXIT_SUCCESS;}


運行示範

jesson@jesson-HP:~/develop/workspace/c_learning/csdn/Prim$ gcc -o Prim Prim.cjesson@jesson-HP:~/develop/workspace/c_learning/csdn/Prim$ ./Prim Please input graph type DG(0) or UDG(1) :1Please input vexmun : 4Please input arcnum : 5Please input 1th vex(char):aPlease input 2th vex(char):bPlease input 3th vex(char):cPlease input 4th vex(char):dPlease input 1th arc v1(char) v2(char) weight(int): a b 1Please input 2th arc v1(char) v2(char) weight(int): a c 3Please input 3th arc v1(char) v2(char) weight(int): a d 4Please input 4th arc v1(char) v2(char) weight(int): b c 2Please input 5th arc v1(char) v2(char) weight(int): c d 3Please input the start vex(char):aThe result of Prim:a b 1b c 2c d 3



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.