繁体   English   中英

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

[英]Time Complexity of Array based Disjoint-Set data structure

我在CodeChef上解决了这个问题,并进行了社论

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

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)

union find的时间复杂度是多少?

IMO, find的时间复杂度为O(depth) ,因此在最坏的情况下,如果我不使用路径约束,则复杂度为O(n)。 由于union还使用find ,因此它也具有O(n)的复杂度。 相反,如果我们扔出去的find来自union ,而是通过两个集合的家长union ,复杂性union是O(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为make set操作数

结合按等级压缩和路径压缩:O(m * p(n))其中p(n)小于等于4

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

如果仅按等级使用联合,而没有路径压缩,则复杂度将是对数的。
详细的解决方案很难理解,但是基本上您不会遍历整个树,因为只有当两组的秩相等时,树的深度才会增加。 因此,每个查询的迭代次数将为O(log * n)。

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

暂无
暂无

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

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