class UnionFind:
def __init__(self, n):
self.count = n
self.p = [i for i in range(n)]
def parent(self, i):
root = i
while self.p[root] != root:
root = self.p[root]
while self.p[i] != i:
x = i
i = self.p[i]
self.p[x] = root
return root
def union(self, i, j):
p1 = self.parent(self.p, i)
p2 = self.parent(self.p, j)
self.p[p1] = p2
Leetcode 并查集模板
最新推荐文章于 2023-06-26 14:25:00 发布
该博客详细介绍了并查集(Disjoint Set)的数据结构及其使用。通过`parent`方法查找元素根节点,并通过`union`方法合并两个集合。这个数据结构在解决不相交集合的问题中非常有效,常见于解决连通性问题,如路径压缩和路径查找等。
摘要由CSDN通过智能技术生成