如果您有足够的节点(例如几亿),那么您可以使用存储在内存中的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可能增加计算时间。
您是否有估计可能涉及多少个节点,边缘和组件?另外,你是否需要完美的精度,还是近似值可以接受? –