woonie

Untitled

Oct 3rd, 2012
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Union-find Disjoint Sets
  2.  
  3. public UnionFind(int N){
  4.     parent = new int[N];
  5.     rank = new int[N]; //all 0
  6.     numSets = N;
  7.     for (int i = 0; i < N; i++){
  8.         parent[i] = i;
  9.     }
  10. }
  11. public void unionSet(int i, int j){
  12.     if (!isSameSet(i, j)){ numSets--;
  13.         int x = findSet(i),  y = findSet(j); //root of i and j
  14.         // rank is used to keep the tree short
  15.         if (rank[x] > rank[y])
  16.             parent[y] = x;
  17.         else
  18.             parent[x] = y;
  19.         if (rank [x] == rank[y])
  20.             rank[y]++;
  21.     }
  22. }
Advertisement
Add Comment
Please, Sign In to add comment