Advertisement
Guest User

dsets.cpp

a guest
Apr 28th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. /**
  2. *  Class implementation of Disjoint sets
  3. */
  4.  
  5. #include "dsets.h"
  6.  
  7. void DisjointSets::addelements(int num)
  8. {
  9.     for (int i = 0; i < num; i++)
  10.     {
  11.         array.push_back(-1);
  12.     }
  13. }
  14.  
  15. int DisjointSets::find(int elem)
  16. {
  17.     if(array[elem] < 0)
  18.     {
  19.         return elem;
  20.     }
  21.     else
  22.     {
  23.         return(array[elem] = find(array[elem]));
  24.     }
  25. }
  26.  
  27. void DisjointSets::setunion( int a, int b )
  28. {
  29.     int root_a=find(a);
  30.     int root_b=find(b);
  31.     if(root_a!=root_b)
  32.     {
  33.         if((-1)*array[root_a]<(-1)*array[root_b])
  34.         {
  35.             array[root_b]+=array[root_a];
  36.             array[root_a]=root_b;
  37.         }
  38.         else
  39.         {
  40.             array[root_a]+=array[root_b];
  41.             array[root_b]=root_a;
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement