[英]Time Complexity of Array based Disjoint-Set data structure
这是已实现的不交集算法的伪代码:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.