Пример #1
0
 void remove() {
   UFNode root = this.find();
   if (root != this) for (UFNode child : children) child.parent = root;
   else if (!children.isEmpty()) {
     Iterator<UFNode> it = children.iterator();
     root = it.next();
     root.parent = null;
     while (it.hasNext()) it.next().parent = root;
     root.size = this.size;
   }
   root.size--;
   this.parent = null;
   this.size = 1;
 }
Пример #2
0
    UFNode find() {
      UFNode root = this;
      while (root.parent != null) root = root.parent;

      UFNode ptr = this;
      while (ptr != root) {
        UFNode old = ptr;
        ptr = ptr.parent;
        ptr.children.remove(old);
        old.parent = root;
        root.children.add(old);
      }
      return root;
    }
Пример #3
0
    int merge(UFNode x) {
      x = x.find();
      UFNode y = this.find();

      if (x != y) {
        if (x.size < y.size) {
          UFNode temp = x;
          x = y;
          y = temp;
        }
        x.size += y.size;
        y.size = 0;
        y.parent = x;
        x.children.add(y);
      }

      return x.size;
    }