Prim and Dijistra algorithm has the same wonderful, but Dijistra is to find the shortest path, each time added to the set is the shortest distance to the fixed starting point, and Prim is to find the smallest spanning tree, is the entire graph of the smallest ownership weight, each added to the collection is the shortest distance to the entire set of points.
The prim algorithm is detailed as follows:
1#include <iostream>2 3 using namespacestd;4 5 #defineINF 1e76 #defineMaxnode 1007 8 BOOLFlag[maxnode];9 intClosest[maxnode];Ten intLowcost[maxnode]; One A voidPrimintNintU0,intMap[maxnode][maxnode]); - - intMain () { the intN, M, U, V, W; -cout <<"Please enter the number of nodes N and the number of sides m:"; -CIN >> N >>m; -cout <<"Please enter the weight of the node edge:"; + intMap[maxnode][maxnode]; - for(inti =0; I < n; i++) { + for(intj =0; J < N; J + +) AMAP[I][J] =INF; at } - for(inti =0; I < m; i++) { -cin >> u >> v >>W; -MAP[U][V] = Map[v][u] =min (w, map[u][v]); - } -cout <<"Please enter a start point:"; in intu0; -CIN >>u0; to Prim (n, u0, map); + intsum =0; - for(inti =0; I < n; i++){ theSum + =Lowcost[i]; * } $cout<<sum;Panax Notoginseng return 0; - } the + voidPrimintNintw0nintMap[maxnode][maxnode]) { A //Initialize theFLAG[U0] =true; + for(inti =0; I < n; i++) { - if(I! =u0) { $Lowcost[i] =Map[u0][i]; $Closest[i] =u0; -}Else { -Lowcost[i] =0; the } - }Wuyi //start looking for the nearest point the for(inti =0; I < n1; i++) { - intm =INF; Wu inttemp =u0; - for(intj =0; J < N; J + +) { About if(Flag[j] = =false&& Lowcost[j] <m) { $m =Lowcost[j]; -temp =J; - } - } A if(temp = =u0) { + Break; the } -Flag[temp] =true; $ for(intj =0; J < N; J + +){ the if(Flag[j] = =false&& Lowcost[j] >Map[j][temp]) { theLOWCOST[J] =Map[j][temp]; theCLOSEST[J] =temp; the } - } in } the}
The prim of greedy algorithm