简体   繁体   English

union如何找到二次算法?

[英]How is union find quadratic algorithm?

In this implementation of Quick Find algorithm, Constructor takes N steps so does union() . 在快速查找算法的这个实现中,构造函数采用N步,因此union()

The instructor said that union is too expensive as it takes N^2 to process sequence of N union commands on N objects, How can union be quadratic when it accesses array elements one at a time? 指导者说union太昂贵,因为它需要N^2来处理N对象上的N union命令的序列。 当一次访问一个数组元素时, union如何是二次的?

public class QuickFind
{
    private int[] id;

    public QuickFind(int N) {
        id = new int[N];
        for (int i=0; i<N; i++) {
            id[i] = i;
        }
    }

    public boolean connected(int p, int q) {
        return id[p] == id[q];
    }

    public void union(int p, int q) {
        int pid = id[p];
        int qid = id[q];

        for (int i=0; i<id.length; i++)
            if (id[i] == pid)
                id[i] = qid;
    }
}

Each invocation of union method requires you iterate over the id array, which takes O(n) time. 每次调用union方法都需要迭代id数组,这需要花费O(n)时间。 If you invoke union method n times, then the time required is n*O(n) = O(n^2) . 如果你调用union方法n次,那么所需的时间是n*O(n) = O(n^2)

You can improve time complexity of union method to O(1) , by making the time complexity of connected method higher, probably O(log n) , but this is just one time operation. 通过使连接方法的时间复杂度更高,可能是O(log n) ,你可以将union方法的时间复杂度提高到O(1) O(log n) ,但这只是一次操作。 I believe that your text book explain this in details. 我相信你的教科书会详细解释这一点。

Union operation for Quick Find is quadratic O(n^2) for n operations, because each operation takes O(n) time, as is easy to notice in for loop inside union(int p, int q) 快速查找的 Union运算对于O(n^2) n运算是二次O(n^2) ,因为每个运算需要O(n)时间,因为很容易注意到for循环内部union(int p, int q)

    for (int i=0; i<id.length; i++)

Notice that the algorithm is called Quick Find , as each find ( connected(int p, int q) ) operation takes constant time. 请注意,该算法称为“ 快速查找” ,因为每个查找( connected(int p, int q) )操作都需要恒定的时间。 However for this algorithm you end up paying in union operation, as mentioned in your question. 但是对于这个算法,你最终会在union操作中支付,如你的问题所述。

There is another algorithm Quick Union , which improves time for union operation. 还有另一种算法Quick Union ,它可以缩短union操作的时间。 But then find doesn't remain O(1) (but better than linear time). 但是后来find并不是O(1) (但比线性时间更好)。

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

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