void Kruskal(Graph& G, Edge* &MST) { ParTree<int> A(G.verticesNum()); //等价类 minHeap<Edge> H(G.edgesNum()); //最小值堆(minheap) MST=new Edge[G.verticesNum()-1]; //最小支撑树 int MSTtag=0; //最小支撑树边的标号 for(int i=0; i<G.verticesNum(); i++) //将图的所有边插入最小值堆H中 for(Edge e= G. firstEdge(i); G.isEdge(e);e=G. nextEdge(e)) if(G.fromVertex(e)< G.toVertex(e)) //因为是无向图,所以应防止重复插入 H.insert(e); int EquNum=G.verticesNum(); //开始时有|V|个等价类 while(EquNum>1) { //合并等价类 Edge e=H.removeMin(); //获得下一条权最小的边 if(e.weight==INFINITE) { std::cout << "不存在最小支撑树." <<std::endl; delete [] MST; //释放空间 MST=NULL; //MST是空数组 return; } int from=G.fromVertex(e); //记录该条边的信息 int to= G.toVertex(e); if(A.Different(from,to)) { //如果边e的两个顶点不在一个等价类 A.Union(from,to); //将边e的两个顶点所在的两个等价类合并为一个 AddEdgetoMST(e,MST,MSTtag++); //将边e加到MST EquNum--; //将等价类的个数减1 } } }
// Prim's MST algorithm: priority queue version void Prim(Graph* G, int* D, int s) { int i, v, w; // "v" is current vertex int V[G->n()]; // V[I] stores I's closest neighbor DijkElem temp; DijkElem E[G->e()]; // Heap array with lots of space temp.distance = 0; temp.vertex = s; E[0] = temp; // Initialize heap array heap<DijkElem, DDComp> H(E, 1, G->e()); // Create heap for (i=0; i<G->n(); i++) { // Now build MST do { if(H.size() == 0) return; // Nothing to remove temp = H.removefirst(); v = temp.vertex; } while (G->getMark(v) == VISITED); G->setMark(v, VISITED); if (v != s) AddEdgetoMST(V[v], v); // Add edge to MST if (D[v] == INFINITY) return; // Ureachable vertex for (w=G->first(v); w<G->n(); w = G->next(v,w)) if (D[w] > G->weight(v, w)) { // Update D D[w] = G->weight(v, w); V[w] = v; // Update who it came from temp.distance = D[w]; temp.vertex = w; H.insert(temp); // Insert new distance in heap } } }
void Kruskel(Graph* G) { // Kruskal's MST algorithm ParPtrTree A(G->n()); // Equivalence class array KruskElem E[G->e()]; // Array of edges for min-heap int i; int edgecnt = 0; for (i=0; i<G->n(); i++) // Put the edges on the array for (int w=G->first(i); w<G->n(); w = G->next(i,w)) { E[edgecnt].distance = G->weight(i, w); E[edgecnt].from = i; E[edgecnt++].to = w; } // Heapify the edges heap<KruskElem, Comp> H(E, edgecnt, edgecnt); int numMST = G->n(); // Initially n equiv classes for (i=0; numMST>1; i++) { // Combine equiv classes KruskElem temp; temp = H.removefirst(); // Get next cheapest edge int v = temp.from; int u = temp.to; if (A.differ(v, u)) { // If in different equiv classes A.UNION(v, u); // Combine equiv classes AddEdgetoMST(temp.from, temp.to); // Add edge to MST numMST--; // One less MST } } }