prim算法也遵循贪婪原则,所以也属于贪婪算法,它用来生成一棵最小消耗生成树template<class T> bool Prim(EdgeNode<T> t[]) { //如果不连通则返回false //如果连通,则在t[0->n-2]中返回最小生成树 int n = Vertices(); bool *selected = new bool [n+1]; VertexNode1<T> *VN1 = new VertexNode1<T> [n+1]; VN1[1].distance = 0; for (int i = 2; i <= n; i++) { VN1[i].distance = -1; selected[i] = false; } InitializePos(); int v; T w; VertexNode2<T> VN2; ModifiedMinHeap<T> *H; H = new ModifiedMinHeap<T> (n); First(1,v,w); while (v) { VN1[v].distance = w; VN1[v].nbr = 1; VN2.ID = v; VN2.distance = w; H->Insert(VN2); Next(1,v,w); } for (int i = 0; i < n - 1; i++) { // 获得最近的没有被选择的点 try { H->DeleteMin(VN2); } catch (OutOfBounds) { return false; } EdgeNode<T> x; int u = VN2.ID; x.u = u; x.v = VN1[u].nbr; x.weight = VN1[u].distance; t[i] = x; selected[u] = true; First(u,v,w); while (v) { // VN1[v].distance 也许会发生改变 if (!selected[v]) { if (VN1[v].distance == -1) { // v 还不在最小堆里 VN1[v].distance = w; VN1[v].nbr = u; VN2.distance = w; VN2.ID = v; H->Insert(VN2); } else if (VN1[v].distance > w) { // v 已经在最小堆了 VN1[v].distance = w; VN1[v].nbr = u; VN2.distance = w; VN2.ID = v; H->Decrease(VN2); } } Next(u,v,w); } } DeactivatePos(); delete [] VN1; delete [] selected; delete H; return true; }