Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. public class QuickUnion {
  2. private int[] id; // id[i] = parent of i
  3. private int count; // number of components
  4.  
  5. // instantiate N isolated components 0 through N-1
  6. public QuickUnion(int N) {
  7. id = new int[N];
  8. count = N;
  9. for (int i = 0; i < N; i++) {
  10. id[i] = i;
  11. }
  12. }
  13.  
  14. // return number of connected components
  15. public int count() {
  16. return count;
  17. }
  18.  
  19. // return root of component corresponding to element p
  20. public int find(int p) {
  21. while (p != id[p])
  22. p = id[p];
  23. return p;
  24. }
  25.  
  26. // are elements p and q in the same component?
  27. public boolean connected(int p, int q) {
  28. return find(p) == find(q);
  29. }
  30.  
  31. // merge components containing p and q
  32. public void union(int p, int q) {
  33. int i = find(p);
  34. int j = find(q);
  35. if (i == j) return;
  36. id[i] = j;
  37. count--;
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement