简体   繁体   English

带路径压缩的加权快速联合

[英]Weighted Quick Union with Path Compression

According to the Princeton booksite, the Weighted Quick Union with Path Compression reduces the time of 10^9 union operations on 10^9 objects from a year to ~6 seconds. 根据普林斯顿大学的书院,带路径压缩的加权快速联合将对10 ^ 9个对象执行10 ^ 9联合操作的时间从一年减少到了约6秒。 How is this number derived? 这个数字是如何得出的? When I run the following code at 10^8 operations I have a runtime of 61s. 当我以10 ^ 8的速度运行以下代码时,我的运行时间为61s。

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];
        }
    }   
}

You can't directly compare this since the runtime depends on many different factors mostly in this case on your CPU performance. 您无法直接进行比较,因为运行时主要取决于许多不同的因素,在这种情况下,取决于您的CPU性能。

Let's say a year has about 31556952 seconds on average (60*60*24*365.2425) And with Path Compression it takes ~6 seconds 假设一年平均大约有31556952秒(60 * 60 * 24 * 365.2425),使用路径压缩大约需要6秒

This means that the Quick Union with path Compression is about 5259492 (31556952/6) times faster than without. 这意味着带有路径压缩的快速联合的速度比没有压缩的速度快约5259492(31556952/6)倍。

So the number given just show how incredible good the performance boost is when you "just" improve the algorithm a bit. 因此,给出的数字仅表明当您“只是”对算法进行一点改进时,性能提升的效果令人难以置信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM