算法导论 ch23 最小生成树 Prim

/* * get the MST using Prim algorithm * sv : start vertex */ void AdjMatrixGraph::mst_prim(int sv){ // the min distance to the current MST int *d = new int[v]; // the parent in the MST int *p = new int[v]; // has the vertex been selected? bool *selected = new bool[v]; for(int i = 0; i < v; i++){ p[i] = -1; d[i] = std::numeric_limits<int>::max(); selected[i] = false; } d[sv] = 0; selected[sv] = true; int selectedV = sv; for(int i = 0; i < v; i++){ // update distance and parent for(int i = 0; i < v; i++){ if(!selected[i]){ if (d[i] > A[selectedV * v + i]){ d[i] = A[selectedV * v + i]; p[i] = selectedV; } } } int vToBeSelected; int distance = std::numeric_limits<int>::max(); // find the vertex which has not been selected with the min distance for(int i = 0; i < v; i++){ if(!selected[i]){ if (d[i] < distance){ distance = d[i]; vToBeSelected = i; } } } //cout << "now selecting vertex is " << vToBeSelected << ", and distance is " << distance << endl; selectedV = vToBeSelected; selected[vToBeSelected] = true; } int weight = 0; for(int i = 0; i < v; i++){ weight += d[i]; cout << "vertex " << i << " is selected with parent " << p[i] << ", and distance is " << d[i] << endl; } cout << "weight of MST is " << weight << endl; }

 

test program:

 

#include "../ch22/Edge.h" #include "../ch22/Graph.h" #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { Edge e[] = { { 1, 2, 4 }, { 1, 8, 8 }, { 2, 8, 11 }, { 2, 3, 8 }, { 3, 4, 7 }, { 3, 6, 4 }, { 3, 9, 2 }, { 4, 5, 9 }, { 4, 6, 14 }, { 5, 6, 10 }, { 6, 7, 2 }, { 7, 8, 1 }, { 7, 9, 6 }, { 8, 9, 7 } }; Edges* edges = Edges::getInstance(); for (unsigned int i = 0; i < sizeof(e)/sizeof(Edge); i++) { edges->insert(&(e[i])); } int numberOfVertexes = 9; AdjMatrixGraph *g1 = new AdjMatrixGraph(numberOfVertexes, edges, false, true); MatrixGraphBuilder* mgb = MatrixGraphBuilder::getInstance(); g1->build(mgb); //g1->display(); g1->mst_prim(0); }

 

run result:

vertex 0 is selected with parent -1, and distance is 0 vertex 1 is selected with parent 0, and distance is 4 vertex 2 is selected with parent 1, and distance is 8 vertex 3 is selected with parent 2, and distance is 7 vertex 4 is selected with parent 3, and distance is 9 vertex 5 is selected with parent 2, and distance is 4 vertex 6 is selected with parent 5, and distance is 2 vertex 7 is selected with parent 6, and distance is 1 vertex 8 is selected with parent 2, and distance is 2 weight of MST is 37

 

你可能感兴趣的:(算法导论 ch23 最小生成树 Prim)