最小產生樹實現

來源:互聯網
上載者:User

最小產生樹的引入是基於城市之間建立通訊網。在建設當中構造連通網的最小代價產生樹,也就是一棵樹,每個節點之間都可以到達,並且圖中邊的權值和最小。以資料分析的角度來看待這個問題就是,在圖中邊集挑選最短的n-1條邊。其中有兩種演算法:Prim和Kruskal。一個是對點展開工作,一個是對邊展開工作。在實現的時候用closedge儲存每個節點到最小樹的距離,同時標記一個節點時候加入這棵樹。
#include "graph.h"
#include <stdio.h>
/*********************************************/
/*          最小產生樹演算法                   */
/*          參數:G  開始點                  */
/*          功能                           */
/*********************************************/
void MiniSpanTree_PRIM(const MGraph *g,const int VerNum)
{
int closedge[MAX_VERTEX_NUM];          //記錄節點到樹的權值 
int i;
//得到起始點鄰接的點權值
    //不鄰接的都是最大值 
for(i=0;i<g->vexnum;i++)                
{
closedge[i] = g->arcs[VerNum][i];
}
//值為0表明該點已加入樹 
closedge[VerNum] = 0;
//逐漸構建樹,每次加入一個點 
for(int j=0;j<g->vexnum-1;j++)
{
      int temp = INT_MAX;        //記錄最小權值 
      int vtemp = 0;             //記錄將加入點
            //尋找到最小權值點 
        for(i=0;i<g->vexnum;i++)
{
if(closedge[i]&&(temp > closedge[i]))
{
temp = closedge[i];
vtemp = i;
}
}
  printf("The node[%d]:%d\n",vtemp,temp);
//由於樹改變了,所以改變每個節點到樹的值 
  for(i=0;i<g->vexnum;i++)
{
if(closedge[i] > g->arcs[vtemp][i])
{
closedge[i] = g->arcs[vtemp][i];
}
}
    closedge[vtemp] = 0;           //設定為加入點 
}
}
/*test
6 10
1 2 3 4 5 6END
1 2 6
1 3 1
1 4 5
2 3 5
2 5 3
3 4 5
3 5 6
3 6 4
4 6 2
5 6 6
end*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.