import java.util.Arrays;

/**
 * Disjoint-set forest packed into one int array.
 *
 * p[x] >= 0 : parent link of a non-root x.
 * p[x] <  0 : x is a root and -p[x] is the size of its set.
 *
 * Union by size (ties: the second root goes under the first), path halving.
 */
public final class UnionFind {
    private final int[] p;
    private final int n;
    private int sets;

    public UnionFind(int n) {
        this.n = n;
        this.sets = n;
        int[] a = new int[n];
        Arrays.fill(a, -1);
        this.p = a;
    }

    // Root of x, given px = p[x]; path halving along the way.
    private static int root(int[] p, int x, int px) {
        while (px >= 0) {
            int gp = p[px];
            if (gp < 0) return px;
            p[x] = gp;
            x = gp;
            px = p[gp];
        }
        return x;
    }

    public int find(int x) {
        int[] p = this.p;
        return root(p, x, p[x]);
    }

    public boolean union(int a, int b) {
        int[] p = this.p;
        // Load both first so the two cache misses overlap.
        int pa = p[a];
        int pb = p[b];
        int ra = root(p, a, pa);
        int rb = root(p, b, pb);
        if (ra == rb) return false;
        int sa = p[ra];
        int sb = p[rb];
        if (sa > sb) { // set of ra is smaller
            p[rb] = sa + sb;
            p[ra] = rb;
        } else {
            p[ra] = sa + sb;
            p[rb] = ra;
        }
        sets--;
        return true;
    }

    public boolean connected(int a, int b) {
        int[] p = this.p;
        int pa = p[a];
        int pb = p[b];
        return root(p, a, pa) == root(p, b, pb);
    }

    public int setSize(int x) {
        int[] p = this.p;
        return -p[root(p, x, p[x])];
    }

    public int sets() {
        return sets;
    }

    public int size() {
        return n;
    }

    public int parent(int x) {
        int px = p[x];
        return px < 0 ? x : px;
    }
}
