加权路径压缩并查集实现
package algs4; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; import java.io.FileInputStream; import java.io.InputStream; /** * 并查集 * Created by blank on 2015-10-15 下午8:56. */ public class UF { public static void main(String[] args) throws Exception { InputStream input = new FileInputStream(Constants.PATH + "largeUF.txt"); System.setIn(input); int N = StdIn.readInt(); UF uf = new UF(N); while (N-- > 0) { 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.getCount() + " components"); } private int[] parent; private byte[] rank; private int count; public UF(int n) { count = n; parent = new int[n]; rank = new byte[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } } public int getCount() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } private int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) { return; } if (rank[rootP] < rank[rootQ]) { parent[rootP] = rootQ; } else if (rank[rootP] > rank[rootQ]) { parent[rootQ] = rootP; } else { parent[rootP] = rootQ; rank[rootQ]++; } count--; } }