基于数组的不相交集数据结构的时间复杂度

问题描述 投票:1回答:2

我在CodeChef上解决this问题并通过editorial

这是实现的不相交集算法的伪代码:

Initialize parent[i] = i  
Let S[i] denote the initial array.

int find(int i)
    int j
    if(parent[i]==i)
                return i
    else
        j=find(parent[i])
        //Path Compression Heuristics
        parent[i]=j
        return j

set_union(int i,int j)
    int x1,y1
    x1=find(i)
    y1=find(j)
    //parent of both of them will be the one with the highest score
    if(S[x1]>S[y1])
        parent[y1]=x1
    else if ( S[x1] < S[y1])
        parent[x1]=y1

solve()
    if(query == 0)
        Input x and y
        px = find(x)
        py = find(y)
        if(px == py)
            print "Invalid query!"
        else
            set_union(px,py)
    else
        Input x.
        print find(x)

unionfind的时间复杂度是多少?

IMO,find的时间复杂度是O(depth),所以在最坏的情况下,如果我没有使用路径压缩,那么复杂性就变成了O(n)。由于union也使用find,它也具有O(n)的复杂性。相反,如果我们从find扔出union而是将两组的父母传给unionunion的复杂性是O(1)。如果我错了,请纠正我。

如果应用路径压缩,那么时间复杂度是多少?

algorithm disjoint-sets
2个回答
1
投票

没有路径压缩:当我们使用不相交集的链表表示和加权联合启发时,发生m MAKE-SET,UNION by rank,FIND-SET操作的序列,其中n个是MAKE-SET操作。所以,需要O(m + nlogn)。

仅使用路径压缩:运行时间为theta(n + f *(1 +(log(base(2 + f / n))n)))其中f表示查找集操作,n表示不设置操作

通过秩和路径压缩的并集:O(m * p(n))其中p(n)小于等于4


0
投票

如果既不使用秩也不使用路径压缩,则union和find的时间复杂度将是线性的,因为在最坏的情况下,有必要在每个查询中遍历整个树。

如果你只按队列使用union,没有路径压缩,那么复杂性就是对数。 The detailed solution很难理解,但基本上你不会遍历整棵树,因为如果两组的等级相等,树的深度只会增加。因此,每次查询的迭代次数为O(log * n)。

如果使用路径压缩优化,复杂性会更低,因为它会“平坦化”树,从而减少遍历。它的每次操作的摊销时间甚至比O(n)还要快,因为你可以阅读here

© www.soinside.com 2019 - 2024. All rights reserved.