Prim演算法(鄰接矩陣表示的簡單實現)的C++實現


Prim演算法貪婪方法,用於查詢給定帶權重的無向圖的最小生成樹。

加權圖是所有邊都帶權重的圖。

無向圖是一類特殊型別的圖,其中所有邊都是雙向的。

最小生成樹包含所有邊和頂點但無圈,並且具有儘可能小的總邊權的子集。

本文將介紹Prim演算法來查詢最小生成樹。通常,演算法使用兩個陣列,但本解決方案只使用一個。

顯示Prim演算法實現的程式。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
#define V 5
bool createsMST(int u, int v, vector<bool> inMST){
   if (u == v)
      return false;
   if (inMST[u] == false && inMST[v] == false)
      return false;
   else if (inMST[u] == true && inMST[v] == true)
      return false;
   return true;
}
void printMinSpanningTree(int cost[][V]){
   vector<bool> inMST(V, false);
   inMST[0] = true;
   int edgeNo = 0, MSTcost = 0;
   while (edgeNo < V - 1) {
      int min = INT_MAX, a = -1, b = -1;
      for (int i = 0; i < V; i++) {
         for (int j = 0; j < V; j++) {
            if (cost[i][j] < min) {
               if (createsMST(i, j, inMST)) {
                  min = cost[i][j];
                  a = i;
                  b = j;
               }
            }
         }
      }
      if (a != -1 && b != -1) {
         cout<<"Edge "<<edgeNo++<<" : ("<<a<<" , "<<b<<" ) : cost = "<<min<<endl;
         MSTcost += min;
         inMST[b] = inMST[a] = true;
      }
   }
   cout<<"Cost of Minimum spanning tree ="<<MSTcost;
}
int main() {
   int cost[][V] = {
      { INT_MAX, 12, INT_MAX, 25, INT_MAX },
      { 12, INT_MAX, 11, 8, 12 },
      { INT_MAX, 11, INT_MAX, INT_MAX, 17 },
      { 25, 8, INT_MAX, INT_MAX, 15 },
      { INT_MAX, 12, 17, 15, INT_MAX },
   };
   cout<<"The Minimum spanning tree for the given tree is :\n";
   printMinSpanningTree(cost);
   return 0;
}

輸出

The Minimum spanning tree for the given tree is :
Edge 0 : (0 , 1 ) : cost = 12
Edge 1 : (1 , 3 ) : cost = 8
Edge 2 : (1 , 2 ) : cost = 11
Edge 3 : (1 , 4 ) : cost = 12
Cost of Minimum spanning tree =43

更新時間:2020-02-03

4K+ 瀏覽

開啟您的職業生涯

完成課程並獲得認證

開始
廣告