public class WeightedQuickUnionUF { private int[] id; private int[] size; public WeightedQuickUnionUF(int N) { id = new int[N]; size = new int[N]; for (int i = 0; i < N; i++) { id[i] = i; size[i] = 0; } } private int root(int i) { while (i != id[i]) i = id[i]; return i; } //log(N) public boolean connected(int p, int q) { return root(p) == root(q); } //log(N) public void union(int p, int q) { int i = root(p); int j = root(q); if (i == j) return; if (size[i] < size[j]) { id[i] = j; size[j] += size[i]; } else { id[j] = i; size[i] += size[j]; } } }
public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); WeightedQuickUnionUF wQuickUnionUF = new WeightedQuickUnionUF(N); while (in.hasNext()) { int p = in.nextInt(); int q = in.nextInt(); if (!wQuickUnionUF.connected(p, q)) { wQuickUnionUF.union(p, q); } else System.out.println("Already Connected"); } } }