[英]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.