Pabl0o0

Untitled

Jun 7th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. package równoważenie_wysokości;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class Element {
  7.  
  8. int value;
  9. Element parent = null;
  10. int height;
  11. static ArrayList lista = new ArrayList();
  12.  
  13. public Element(int value){
  14. this.value = value;
  15. }
  16.  
  17. static void MAKE_SET(Element x){
  18. x.parent = x;
  19. x.height=0;
  20. lista.add(x);
  21. }
  22.  
  23. static void UNION (Element x , Element y){
  24. LINK(FIND(x),FIND(y));
  25. }
  26.  
  27. static void LINK (Element x, Element y){
  28. if (x.height > y.height)
  29. y.parent=x;
  30. else {
  31. x.parent=y;
  32. if (x.height == y.height)
  33. y.height++;
  34. }
  35. }
  36.  
  37. static Element FIND(Element x ){
  38. return x == x.parent ? x : FIND(x.parent) ;
  39. }
  40.  
  41. static void display(Element x){
  42. if (x.parent.value == x.value){
  43. System.out.print(x.parent.value);
  44. }
  45. else {
  46. while(x.parent.value != x.value){
  47. System.out.print(x.value + "==>" + x.parent.value+ "==>");
  48. display2(x.parent);
  49. break;
  50. }
  51. }
  52. }
  53.  
  54. static void display2(Element x){
  55. if (x.parent.value == x.value){
  56. System.out.print(x.parent.value);
  57. }
  58. else {
  59. while(x.parent.value != x.value){
  60. System.out.print(x.parent.value+ "==>");
  61. display2(x.parent);
  62. break;
  63. }
  64. }
  65. }
  66.  
  67. static void wyswietlListeElementow(){
  68. for (int i =0; i<lista.size();i++){
  69. System.out.println(lista.get(i));
  70. }
  71. }
  72.  
  73.  
  74. public static void main(String []args){
  75. Element a = new Element(10);
  76. Element b = new Element(11);
  77. Element c = new Element(12);
  78. Element d = new Element(13);
  79. Element e = new Element(100);
  80. wyswietlListeElementow();
  81. System.out.println("Lista elementów: "+a.value+" "+b.value+" "+c.value+" "+d.value+ " "+e.value);
  82. System.out.println();
  83. MAKE_SET(a);
  84. MAKE_SET(b);
  85. MAKE_SET(c);
  86. MAKE_SET(d);
  87. MAKE_SET(e);
  88. LINK(a,b);
  89. System.out.println("Łączę 10 z 11:");
  90. display(a);
  91.  
  92. System.out.println("\n");
  93.  
  94. LINK(b,e);
  95. System.out.println("Łączę 100 z 11:");
  96. display(e);
  97.  
  98. System.out.println("\n");
  99.  
  100. LINK(c,d);
  101. System.out.println("Łączę 12 z 13:");
  102. display(c);
  103.  
  104. System.out.println("\n");
  105.  
  106. LINK(d,b);
  107. System.out.println("Łączę 12 z 11:");
  108. display(c);
  109.  
  110. System.out.println("\n");
  111. System.out.println("Całe drzewo");
  112.  
  113. }
  114.  
  115. }
Advertisement
Add Comment
Please, Sign In to add comment