Advertisement
Guest User

Untitled

a guest
Apr 16th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Node{
  4. int data;
  5. Node parent;
  6. int rank;
  7. }
  8.  
  9. public class DisjointSet{
  10. private Map<Integer, Node> map;
  11. DisjointSet(){
  12. map = new HashMap<>();
  13. }
  14.  
  15. public void makeSet(int data){
  16. Node node = new Node();
  17. node.data = data;
  18. node.parent = node;
  19. node.rank = 0;
  20. map.put(data, node);
  21. }
  22.  
  23. private Node findSet(Node node){
  24. if(node.parent == node)
  25. return node;
  26. node.parent = findSet(node.parent);
  27. return node.parent;
  28. }
  29.  
  30. public int findSet(int data){
  31. return findSet(map.get(data)).data;
  32. }
  33.  
  34. public void union(int a, int b){
  35. Node node1 = map.get(a);
  36. Node node2 = map.get(b);
  37. Node representative1 = findSet(node1);
  38. Node representative2 = findSet(node2);
  39. if(representative1.data == representative2.data)
  40. return;
  41. if(representative1.rank >= representative2.rank){
  42. if(representative1.rank == representative2.rank)
  43. representative1.rank = representative2.rank + 1;
  44. representative2.parent = representative1;
  45. }
  46. else
  47. representative1.parent = representative2;
  48. }
  49.  
  50. public static void main(String[] args){
  51. DisjointSet ds = new DisjointSet();
  52. for(int i=1; i<=7; i++)
  53. ds.makeSet(i);
  54.  
  55. ds.union(1, 2); ds.union(2, 3);
  56. ds.union(4, 5); ds.union(6, 7);
  57. ds.union(5, 6); ds.union(3, 7);
  58.  
  59. for(int i=1; i<=7; i++)
  60. System.out.println(i +" -> " +ds.findSet(i));
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement