貪心算法之Prim
阿新 • • 發佈:2018-06-03
nbsp IV min using space 算法 短路徑 最短路徑 AS
Prim與Dijistra算法有異曲同工之妙,只不過Dijistra是求最短路徑,每次添加到集合中的是到固定起始點的最短距離,而Prim是求最小生成樹,是整個圖所有權重的最小和,每次添加到集合中的是到整個集合最短距離的點。
Prim算法具體如下所示:
1 #include <iostream> 2 3 using namespace std; 4 5 #define INF 1e7 6 #define MAXNODE 100 7 8 bool flag[MAXNODE]; 9 int closest[MAXNODE]; 10 int lowcost[MAXNODE];11 12 void prim(int n, int u0, int map[MAXNODE][MAXNODE]); 13 14 int main() { 15 int n, m, u, v, w; 16 cout << "請輸入節點數n和邊數m:"; 17 cin >> n >> m; 18 cout << "請輸入節點邊的權值:"; 19 int map[MAXNODE][MAXNODE]; 20 for (int i = 0; i < n; i++) { 21 for (intj = 0; j < n; j++) 22 map[i][j] = INF; 23 } 24 for (int i = 0; i < m; i++) { 25 cin >> u >> v >> w; 26 map[u][v] = map[v][u] = min(w, map[u][v]); 27 } 28 cout << "請輸入開始點:"; 29 int u0; 30 cin >> u0; 31 prim(n, u0, map);32 int sum = 0; 33 for(int i = 0; i < n; i++){ 34 sum += lowcost[i]; 35 } 36 cout<<sum; 37 return 0; 38 } 39 40 void prim(int n, int u0, int map[MAXNODE][MAXNODE]) { 41 //初始化 42 flag[u0] = true; 43 for (int i = 0; i < n; i++) { 44 if (i != u0) { 45 lowcost[i] = map[u0][i]; 46 closest[i] = u0; 47 } else { 48 lowcost[i] = 0; 49 } 50 } 51 //開始找最近點 52 for (int i = 0; i < n-1; i++) { 53 int m = INF; 54 int temp = u0; 55 for(int j = 0; j < n; j++) { 56 if (flag[j] == false && lowcost[j] < m){ 57 m = lowcost[j]; 58 temp = j; 59 } 60 } 61 if(temp == u0){ 62 break; 63 } 64 flag[temp] = true; 65 for(int j = 0; j < n; j++){ 66 if(flag[j] == false && lowcost[j] > map[j][temp]){ 67 lowcost[j] = map[j][temp]; 68 closest[j] = temp; 69 } 70 } 71 } 72 }
貪心算法之Prim