1. Kruskal 实现 1) MSTEdge.h #ifndef MSTEDGE_H_ #define MSTEDGE_H_ #include <iostream> using namespace std; /* * Edge class for MST */ class MSTEdge { public: int from; int to; int weight; public: bool operator < (MSTEdge &that){ return weight < that.weight; } }; ostream& operator <<(ostream& os, MSTEdge &e); #endif /*MSTEDGE_H_*/ 2) MSTEdge.cpp #include "MSTEdge.h" ostream& operator <<(ostream& os, MSTEdge &q) { os << "("<< q.from<< ", "<< q.to<< ", "<< q.weight<< ")"; return os; } 3) Kruskal.cpp #include "MSTEdge.h" #include <iostream> #include <vector> #include <algorithm> using namespace std; bool MSTEdgeCompare(MSTEdge i, MSTEdge j) { return (i<j); } int findSet(int p[], int numberOfVertexes, int v) { while(p[v] != v) { v = p[v]; } return v; } void unionSet(int **p, int x, int y) { do{ int py = (*p)[y]; (*p)[y] = x; y = py; }while((*p)[y] != x); // for (int i = 0; i < 10; i++) { // cout << (*p)[i] << " "; // } // cout << endl; } void mst_kruskal(MSTEdge e[], unsigned int numberOfEdges, int numberOfVertexes) { int* p = new int[numberOfVertexes + 1]; for (int i = 0; i < numberOfVertexes + 1; i++) { p[i] = i; } vector<MSTEdge> vecEdges(e, e + numberOfEdges); vector<MSTEdge> mst; sort(vecEdges.begin(), vecEdges.end(), MSTEdgeCompare); vector<MSTEdge>::iterator it; for (it = vecEdges.begin(); it != vecEdges.end(); ++it) { cout <<"now checking edge "<< *it << endl; int from = (*it).from; int to = (*it).to; int fromSet = findSet(p, numberOfVertexes, from ); int toSet = findSet(p, numberOfVertexes, to); // cout << "p of " << from << " is " << fromSet << endl; // cout << "p of " << to << " is " << toSet << endl; if(fromSet != toSet){ // find an tree edge mst.push_back(*it); unionSet(&p, from, to); } } int weight = 0; cout << "The MST constructed using Kruskal algorithm is " << endl; for (it = mst.begin(); it != mst.end(); ++it) { cout << *it << endl; weight += (*it).weight; } cout << "Weight is " << weight << endl; // for (int i = 0; i < numberOfVertexes + 1; i++) { // cout << p[i] << " "; // } // cout << endl; } int main() { MSTEdge 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 } }; unsigned int numberOfEdges = sizeof(e)/sizeof(MSTEdge); mst_kruskal(e, numberOfEdges, 9); } 4) run result now checking edge (7, 8, 1) now checking edge (3, 9, 2) now checking edge (6, 7, 2) now checking edge (1, 2, 4) now checking edge (3, 6, 4) now checking edge (7, 9, 6) now checking edge (3, 4, 7) now checking edge (8, 9, 7) now checking edge (1, 8, 8) now checking edge (2, 3, 8) now checking edge (4, 5, 9) now checking edge (5, 6, 10) now checking edge (2, 8, 11) now checking edge (4, 6, 14) The MST constructed using Kruskal algorithm is (7, 8, 1) (3, 9, 2) (6, 7, 2) (1, 2, 4) (3, 6, 4) (3, 4, 7) (1, 8, 8) (4, 5, 9) Weight is 37