根据普林斯顿书店的说法,带有路径压缩的加权快速联合将 10^9 个对象的 10^9 联合操作的时间从一年减少到约 6 秒。这个数字是如何得出的?当我以 10^8 次操作运行以下代码时,我的运行时间为 61 秒。
public class MainWQUPC{
public static void main(String[] args){
int p, q;
Scanner s = new Scanner(System.in);
long N = s.nextLong();
WQUPC uf = new WQUPC((int) N);
for(int x = 0; x < N; x++){
p = (int) (Math.random() * N);
q = (int) (Math.random() * N);
if(!uf.connected(p, q))
uf.union(p, q);
}
}
}
public class WQUPC{
private int[] id;
private int[] sz;
public WQUPC(int N){
id = new int[N];
sz = new int[N];
for(int i = 0; i < N; i++){
id[i] = i;
sz[i] = 1;
}
}
int root(int i){
while(i != id[i]){
id[i] = id[id[i]];
i = id[i];
}
return i;
}
boolean connected(int p, int q){
return root(p) == root(q);
}
void union(int p, int q){
int i = root(p);
int j = root(q);
if(sz[i] < sz[j]){
id[i] = j;
sz[j] += sz[i];
}else{
id[j] = i;
sz[i] += sz[j];
}
}
}