union-find
package unionfind;
import java.io.IOException;
public class UnionFind {
private int[] id;
private int count;
public UnionFind(int N) {
count = 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) {return id[p];}
public void union(int p , int q) {
int pID = find(p);
int qID = find(q);
if(pID == qID) return;
for(int i=0;i<id.length;i++)
if(id[i] == pID) id[i] = qID;
count--;
}
quick-union
package unionfind;
public class QuickUnion {
private int count;
private int[] id;
public int count() {return count;}
public QuickUnion(int N) {
count = N;
for(int i=0;i<N;i++) {
id[i] = i;
}
}
public int find(int p) {
while(p != id[p]) p = id[p];
return p;
}
public void union(int p,int q) {
int proot = find(p);
int qroot = find(q);
if(proot == qroot) return;
id[proot] = qroot;
count--;
}
}
weighted-Quick-union
package unionfind;
public class WeightedQuickUnion {
private int count;
private int[] id;
private int[] sz;
public WeightedQuickUnion(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 int find(int p) {
while(p != id[p]) p = id[p];
return p;
}
public boolean connected(int q,int p) {return find(q) == find(p);}
public void union(int q,int p) {
int qroot = find(q);
int proot = find(p);
if(qroot == proot) return;
if(sz[qroot] < sz[proot]) {id[qroot] = proot; sz[proot] += sz[qroot];}
else { id[proot] = qroot;sz[qroot] += sz[proot];}
}
}