Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. public class QuickUnion implements DisjointSets{
  2. private int[] parent;
  3.  
  4. /* O(N) */
  5. public QuickUnion(int N){
  6. parent = new int[N];
  7. for (int i = 0; i < N; i++){
  8. parent[i] = i;
  9. }
  10. }
  11.  
  12. private int findRoot(int p){
  13. /* Add Path Compression:
  14. tie all nodes passed through to the ROOT
  15. => iterated log scale lg* N
  16. Implementation: Using Recursion !!! recursive up and down !!! */
  17. int nodeParent = parent[p];
  18. if (p == parent[p]){
  19. return p;
  20. } else {
  21. parent[p] = findRoot(parent[p]);
  22. return parent[p];
  23. }
  24. }
  25.  
  26. /* need to iterate through the array ! => O(N) */
  27. public void connect(int p, int q){
  28. int pRoot = findRoot(p);
  29. int qRoot = findRoot(q);
  30. parent[qRoot] = pRoot;
  31. return;
  32. }
  33.  
  34. /* very fast */
  35. public boolean isConnected(int p, int q){
  36. return (findRoot(p) == findRoot(q));
  37. }
  38.  
  39. public static void main(String[] args) {
  40. QuickUnion qf = new QuickUnion(10);
  41. qf.connect(1, 2);
  42. qf.connect(1, 3);
  43. qf.connect(2, 4);
  44. qf.connect(0, 3);
  45. System.out.println(qf.isConnected(0, 4));
  46. System.out.println(qf.isConnected(3, 6));
  47. }
  48. }
  49.  
  50.  
  51. public interface DisjointSets {
  52.  
  53. void connect(int p, int q);
  54.  
  55. boolean isConnected(int p, int q);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement