如果节点数量很少(例如几亿个),则可以通过在内存中使用
不相交集森林来一次遍历文本文件计算连接组件。
该数据结构仅存储每个节点的等级和父指针,因此如果节点很少,则应适合于内存中。
对于更多的节点,可以尝试相同的想法,但将数据结构存储在磁盘上(并可能通过使用缓存在内存中存储频繁使用的项来改进)。
以下是一些实现简单的内存不相交集森林的Python代码:
N=7
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)
如果您将其应用于名为disjointset.txt的文本文件,其中包含:
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
您可以不使用等级数组来节省内存,但可能会增加计算时间的成本。