Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. public class WeightedQuickUnion {
  2. private int[] id; // id[i] = parent of i
  3. private int[] sz; // sz[i] = number of objects in subtree rooted at i
  4. private int count; // number of components
  5.  
  6. // Create an empty union find data structure with N isolated sets.
  7. public WeightedQuickUnion(int N) {
  8. count = N;
  9. id = new int[N];
  10. sz = new int[N];
  11. for (int i = 0; i < N; i++) {
  12. id[i] = i;
  13. sz[i] = 1;
  14. }
  15. }
  16.  
  17. // Return the number of disjoint sets.
  18. public int count() {
  19. return count;
  20. }
  21.  
  22. // Return component identifier for component containing p
  23. public int find(int p) {
  24. while (p != id[p])
  25. p = id[p];
  26. return p;
  27. }
  28.  
  29. // Are objects p and q in the same set?
  30. public boolean connected(int p, int q) {
  31. return find(p) == find(q);
  32. }
  33.  
  34.  
  35. // Replace sets containing p and q with their union.
  36. public void union(int p, int q) {
  37. int i = find(p);
  38. int j = find(q);
  39. if (i == j) return;
  40.  
  41. // make smaller root point to larger one
  42. if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; }
  43. else { id[j] = i; sz[i] += sz[j]; }
  44. count--;
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement