如果您有足夠的節點(例如幾億),那麼您可以使用存儲在內存中的disjoint set forest,通過文本文件單遍計算連接的組件。
這個數據結構只存儲每個節點的等級和父指針,所以如果你有足夠的節點,應該適合內存。對於較大數量的節點,您可以嘗試相同的想法,但將數據結構存儲在磁盤上(並可能通過在內存中使用高速緩存來存儲經常使用的項目)。
這裏是實現一個簡單的內存版本分離集森林的一些Python代碼:如果你把它應用到包含所謂的文本文件disjointset.txt
N=7 # Number of nodes
rank=[0]*N
parent=range(N)
def Find(x):
"""Find representative of connected component"""
if parent[x] != x:
parent[x] = Find(parent[x])
return parent[x]
def Union(x,y):
"""Merge sets containing elements x and y"""
x = Find(x)
y = Find(y)
if x == y:
return
if rank[x]<rank[y]:
parent[x] = y
elif rank[x]>rank[y]:
parent[y] = x
else:
parent[y] = x
rank[x] += 1
with open("disjointset.txt","r") as fd:
for line in fd:
fr,to = map(int,line.split())
Union(fr,to)
for n in range(N):
print n,'is in component',Find(n)
:
1 2
3 4
4 5
0 5
它打印
0 is in component 3
1 is in component 1
2 is in component 1
3 is in component 3
4 is in component 3
5 is in component 3
6 is in component 6
您可以通過不使用rank數組來節省內存,代價爲o f可能增加計算時間。
您是否有估計可能涉及多少個節點,邊緣和組件?另外,你是否需要完美的精度,還是近似值可以接受? –