/** * Reads in a sequence of pairs of integers (between 0 and N-1) from standard input, where each * integer represents some object; if the objects are in different components, merge the two * components and print the pair to standard output. */ public static void main(String[] args) { int N = StdIn.readInt(); QuickUnionUF uf = new QuickUnionUF(N); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.connected(p, q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } StdOut.println(uf.count() + " components"); }
public static double TrialQuickUnionUF(int N) { Stopwatch watch = new Stopwatch(); QuickUnionUF uf = new QuickUnionUF(N); for (int i = 0; i < N; i++) { int p = StdRandom.uniform(N); int q = StdRandom.uniform(N); if (!uf.connected(p, q)) { uf.union(p, q); } } double time = watch.elapsedTime(); // printTree(uf); return time; }