后面有时间填图。。。。。。
Quick-Find
public class UnionFind {
private int[] element;
public UnionFind(int capcity){
element = new int[capcity];
for (int i = 0;i<capcity;i++){
element[i] = i;
}
}
public int find(int p){
return element[p];
}
public boolean isConnected(int p,int q){
return find(p) == find(q);
}
public void union(int p,int q){
int x = find(p);
int y = find(q);
for(int i=0;i<element.length;i++){
if (element[i] == x) {
element[i] = y;
}
}
}
}
Quick-Union
public class UnionFind {
private int[] element;
public UnionFind(int capcity){
element = new int[capcity];
for (int i = 0;i<capcity;i++){
element[i] = i;
}
}
public boolean isConnected(int p,int q){
return find(p) == find(q);
}
public int find(int p){
while(element[p]!=p){
p = element[p];
}
return p;
}
public void union(int p,int q){
int x = find(p);
int y = find(q);
if(x!=y)
element[x] = y;
}
}
加权Quick-Union
public class UnionFind {
private int[] element;
private int[] weights;
public UnionFind(int capcity){
element = new int[capcity];
weights = new int[capcity];
for (int i = 0;i<capcity;i++){
element[i] = i;
weights[i] = 1;
}
}
public boolean isConnected(int p,int q){
return find(p) == find(q);
}
public int find(int p){
while(element[p]!=p){
p = element[p];
}
return p;
}
public void union(int p,int q){
int x = find(p);
int y = find(q);
if(x == y){
return;
}
if(weights[x]>weights[y]){
element[y] = x;
}else if(weights[x]<weights[y]){
element[x] = y;
}else{
element[x] = y;
weights[y]++;
}
}
}
路径压缩加权Quick-Union
public class UnionFind {
private int[] element;
private int[] weights;
public UnionFind(int capcity){
element = new int[capcity];
weights = new int[capcity];
for (int i = 0;i<capcity;i++){
element[i] = i;
weights[i] = 1;
}
}
public boolean isConnected(int p,int q){
return find(p) == find(q);
}
public int find(int p){
while(element[p]!=p){
element[p] = element[element[p]];
p = element[p];
}
return p;
}
public void union(int p,int q){
int x = find(p);
int y = find(q);
if(x == y){
return;
}
if(weights[x]>weights[y]){
element[y] = x;
}else if(weights[x]<weights[y]){
element[x] = y;
}else{
element[x] = y;
weights[y]++;
}
}
}
比较
算法 | union | find |
---|---|---|
Quick Find | N | 1 |
Quick Union | 树高 | 树高 |
加权 Quick Union | logN | logN |
路径压缩的加权 Quick Union | 非常接近 1 | 非常接近 1 |
上面的算法参考了:https://github.com/CyC2018/CS-Notes/blob/master/notes/算法%20-%20并查集.md