public class UF { private int[] id; //component id (with the contact as an index) private int count; //Number of components public UF(int N) { //initialize the component array count = N; id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; } public int count() { return count; } public boolean connected(int p,int q) { return find(p) == find(q); } public int find(int p) public void union(int p,int q) public static void main(String[] args) { int N = StdIn.readInt(); //Read the number of contacts UF uf = new UF(N); //Initialize N components while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); //read integer pair if (uf.connected(p, q)) continue; //Ignore if already connected uf.union(p, q); // merge components StdOut.println(p + " " + q); //print connection } StdOut.println(uf.count() + "components"); } }
public int find(int p) { return id[p]; } public void union(int p, int q) { // merge p and q into the same component int pID = find(p); int qID = find(q); //p and q are in the same component, no action is taken if (pID == qID) return; //Rename the component of p to the name of q for (int i = 0; i < id.length; i++) if (id[i] == pID) id[i] = qID; count--; }