Advertisement
Ladies_Man

Set Element - Эл-т множества

Nov 10th, 2014
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. public class SetElement<T> {
  2.     private T x;
  3. private int depth;
  4. private SetElement<T> parent, rootx, rooty;
  5.  
  6. public SetElement (T x) {
  7.     this.x = x;
  8.     depth = 0;
  9.     parent = this;
  10. }
  11.  
  12. public T x() {
  13.     return x;
  14. }
  15.  
  16. private SetElement<T> Find (SetElement<T> elem) {
  17.     if (elem.parent == this) {
  18.         return elem.parent;
  19.     } else {
  20.         elem.parent = elem.parent.Find(elem.parent);
  21.         return elem.parent;
  22.     }
  23. }
  24.  
  25. public Boolean equivalent(SetElement<T> elem) {
  26.     rootx = this.Find(this);
  27.     rooty = elem.Find(elem);
  28.     if (rootx == rooty) {
  29.         return true;
  30.     }
  31.     return false;
  32. }
  33.  
  34. public void union (SetElement<T> elem) {
  35.     rootx = this.Find(this);    //union for "a" in "a.union(b)"
  36.     rooty = elem.Find(elem);    //union for "b" in "a.union(b)"
  37.     if (rootx.depth < rooty.depth) {
  38.         rootx.parent = rooty;
  39.     } else {
  40.         rooty.parent = rootx;
  41.         if ((rootx.depth == rooty.depth) && (rootx != rooty)) {
  42.             rootx.depth++;
  43.         }
  44.     }
  45.         return;
  46. }
  47. }
  48.  
  49. //========================================================================================
  50.  
  51. public class Test
  52. {
  53.         public static void main(String[] args)
  54.         {
  55.                 SetElement<Integer> a = new SetElement<Integer> (0),
  56.                         b = new SetElement<Integer> (1),
  57.                         c = new SetElement<Integer> (2),
  58.                         d = new SetElement<Integer> (3),
  59.                         e = new SetElement<Integer> (4),
  60.                         f = new SetElement<Integer> (5);
  61.                 a.union(b);
  62.                 c.union(a);
  63.                 c.union(d);
  64.                 e.union(f);
  65.                 System.out.println("" + a.x() + "=" + d.x() + ":␣" + a.equivalent(d));
  66.                 System.out.println("" + a.x() + "=" + f.x() + ":␣" + a.equivalent(f));
  67.         }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement