public class Based_on_rank_optimize { private int[] parent; private int[] rank; //rank[i]表示以i为根的树层数 private int count; public Based_on_rank_optimize(int n) { // TODO Auto-generated constructor stub this.parent = new int[n]; this.count = n; this.rank = new int[n]; for(int i = 0; i < n; i ++) { parent[i] = i; rank[i] = 1; //有时候用0也是可以的 } } int find(int p) { assert (p >= 0 && p < count); // while(p != parent[p]) { //路径压缩,一般用这个 // parent[p] = parent[parent[p]]; // p = parent[p]; // } // return p; //两种路径压缩 if(p != parent[p]) //逻辑上更优,但由于递归开销大,实践更慢 parent[p] = find(parent[p]); return parent[p]; } boolean isConnected(int p, int q) { return find(p) == find(q); } void unionElements(int p, int q) { int pRoot = find(p); int qRoot = find(q); if(pRoot == qRoot) return; if(rank[pRoot] > rank[qRoot]) { parent[qRoot] = pRoot; } else if(rank[pRoot] < rank[qRoot]){ parent[pRoot] = qRoot; } else { parent[pRoot] = qRoot; rank[qRoot] += 1; } } }