楼主:
dont 2024-08-29 19:49:22你可以把Union Find想成一个树状结构
Find是找树根, Union是把树合并成一棵
初始每个点都是一棵树, 所以root是自己
## Find: 回传该点的树根
Basic: 一直检查父节点, 直到找到树的root
```python
def find(self, x):
while x != self.root[x]:
x = self.root[x]
return x
```
Optimized: path compression
查找root的时候, 顺便把树扁平化 -> 父节点都直接指向root
```python
def find(self, x):
if x != self.root[x]:
self.root[x] = self.find(self.root[x])
return self.root[x]
```
## Union: 如果两点在不同树上, 就把树合并
Basic:
两个点如果连接的话, 表示两点在同一棵树上(树根相同)
如果不相连, 就直接把root_y 的父节点设为 root_x
```python
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
self.root[root_y] = root_x
```
Optimized: Union by Rank
就..比较小的接在大树下
```python
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x == root_y:
return False
if self.rank[root_x] >= self.rank[root_y]:
self.rank[root_x] += self.rank[root_y]
self.root[root_y] = root_x
else:
self.rank[root_y] += self.rank[root_x]
self.root[root_x] = root_y
return True
```
整个合起来 Template大概是这样:
```python
class UnionFind:
def __init__(self, n):
self.root = list(range(n))
self.rank = [1] * n
def find(self, x):
if self.root[x] != x:
self.root[x] = self.find(self.root[x])
return self.root[x]
def union(self, x, y):
rx, ry = self.find(x), self.find(y)
if rx == ry:
return 0
if self.rank[rx] >= self.rank[ry]:
self.rank[rx] += self.rank[ry]
self.root[ry] = rx
else:
self.rank[ry] += self.rank[rx]
self.root[rx] = ry
return 1
```