public class UnionFind {
private int[] id;
private int count;
public UnionFind(int n){
count = n;
id = new int[n];
for(int i = 0 ; i < n ; i++){
id[i] = i;
}
}
public int find( int p ){
assert( p >= 0 && p < count);
return id[p];
}
public boolean isConnected(int p, int q){
return find(p) == find(q);
}
public void unionElements(int p, int q){
int pId = find(p);
int qId = find(q);
if(pId == qId){
return;
}
for(int i = 0 ; i < count ; i++){
if(id[i] == pId){
id[i] = qId;
}
}
}
}
import java.util.Random;
public class Main {
public static void main(String[] args){
int n = 10000;
UnionFind uf = new UnionFind(n);
Random random = new Random(System.currentTimeMillis());
long start = System.currentTimeMillis();
for(int i = 0 ; i < n ; i++){
int a = random.nextInt(n);
int b = random.nextInt(n);
uf.unionElements(a, b);
}
for(int i = 0 ; i < n ; i++){
int a = random.nextInt(n);
int b = random.nextInt(n);
uf.isConnected(a, b);
}
long end = System.currentTimeMillis();
System.out.println((double)(end-start)/1000);
}
}