标签:links ret font count == connect UI connected return
问题
普通的Union-find并查集算法没有加入权重, 可以构造特别的输入使得每次合并的时候高的树HighTree以低的树LowTree的根【root(LowTree)】为新的根, 造成树的不平衡,从而使得效率下降。
用一个新的数组标记节点当前的高,可以用来在合并的时候减少时间。
当然了,这种方法的空间复杂度会提高一倍,看实际情况使用了。
public class WeightedQuickUnionUF { private int[] id; // parent link (site indexed) private int[] sz; // size of component for roots (site indexed) private int count; // number of components public WeightedQuickUnionUF(int N) { count = N; id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; sz = new int[N]; for (int i = 0; i < N; i++) sz[i] = 1; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } private int find(int p) { // Follow links to find a root. while (p != id[p]) p = id[p]; return p; } public void union(int p, int q) { int i = find(p); int j = find(q); if (i == j) return; // Make smaller root point to larger one. if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } count--; } }
标签:links ret font count == connect UI connected return
原文地址:http://www.cnblogs.com/wangzming/p/7895983.html