diff --git a/1.cpp b/1.cpp index e7095b9..50c92b0 100644 --- a/1.cpp +++ b/1.cpp @@ -91,15 +91,7 @@ class subset // A utility function to find set of an element i // (uses path compression technique) -int find(subset subsets[], int i) -{ - // find root and make root as parent of i - // (path compression) - if (subsets[i].parent != i) - subsets[i].parent = find(subsets, subsets[i].parent); - - return subsets[i].parent; -} + // A function that does union of two sets of x and y // (uses union by rank) @@ -122,7 +114,28 @@ void Union(subset subsets[], int x, int y) subsets[yroot].parent = xroot; subsets[xroot].rank++; } -} +} + +void Union(subset subsets[], int x, int y) +{ + int xroot = find(subsets, x); + int yroot = find(subsets, y); + + // Attach smaller rank tree under root of high + // rank tree (Union by Rank) + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + + // If ranks are same, then make one as root and + // increment its rank by one + else + { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } +} // Compare two edges according to their weights. // Used in qsort() for sorting an array of edges diff --git a/2.cpp b/2.cpp index 3b839e9..f9247dd 100644 --- a/2.cpp +++ b/2.cpp @@ -19,14 +19,7 @@ int minKey(int key[], bool mstSet[]) // A utility function to print the // constructed MST stored in parent[] -void printMST(int parent[], int graph[V][V]) -{ - cout<<"Edge \tWeight\n"; - for (int i = 1; i < V; i++) - cout<