常见算法技术解析
1. 并查集(Union-Find)
并查集是一种用于处理不相交集合的合并与查询问题的数据结构。以下是Python实现的并查集类:
class UnionFind:
def __init__(self, n):
self.up_bound = list(range(n))
self.rank = [0] * n
def find(self, x_index):
if self.up_bound[x_index] == x_index:
return x_index
self.up_bound[x_index] = self.find(self.up_bound[x_index])
return self.up_bound[x_index]
def union(self, x_index, y_index):
repr_x = self.find(x_index)
repr_y = self.find(y_index)
if repr_x == repr_y:
# already in the same component
return False
if self.rank[repr_x] == self.rank[repr_y]:
self.rank[repr_x] += 1
self.up_bound[repr_y] = repr_
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



