/* ** This is a C++ representation of Kruskal's ** algorithm for calculating Minimum Spanning ** Tree of a connected undirected weighted graph. It ** requires edgeList presentation of the graph and ** runtime complexity is O(ElogE) */ #include <cstdio> #include <cstring> #include <vector> #include <algorithm> using namespace std; class Edge { public: int u,v,w; Edge(int u_,int v_,int w_) {u=u_,v=v_,w=w_;} bool operator<(const Edge &p) const {return w<p.w;} }; class DisjointSet { int *parent, V,totalSets; int findParent(int u) { if(u==parent[u]) return u; return parent[u]=findParent(parent[u]); } public: DisjointSet(int V_=100) { V=V_, parent=new int[V+5]; initialize(V); } void initialize(int V_=0) { if(!V_) V_=V; for(int i=0;i<V_;i++) parent[i]=i; totalSets=V_; } bool uniteNodes(int u,int v) { int pu=findParent(u), pv=findParent(v); if(pu==pv) return false; parent[pu]=pv; return true; } bool inSameSet(int u,int v) { int pu=findParent(u), pv=findParent(v); return pu==pv; } }; #define MAX 100 vector<Edge> edgeList; DisjointSet ds(MAX+7); int V; int process() { sort(edgeList.begin(), edgeList.end()); ds.initialize(V); int out=0,u,v,w; for(int i=0;i<(int)edgeList.size();i++) { u=edgeList[i].u, v=edgeList[i].v, w=edgeList[i].w; if(ds.inSameSet(u,v)) continue; ds.uniteNodes(u,v); out+=w; } return out; } int main() { /* code */ return 0; }
MST_Kruskal's
Subscribe to:
Posts (Atom)