并查集在LeetCode周赛里面经常会用到,所以可以准备好模板以节省比赛做题时间。
以下并查集类Python3实现修改于chensuim在LeetCode Weekly Contest 130中最后一题1031. 飞地的数量的实现方法。
class DSU(object):
def __init__(self, n):
self.par = [i for i in range(n)]
self.sz = [1] * n
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return
if self.sz[xr] < self.sz[yr]:
xr, yr = yr, xr
self.par[yr] = xr
self.sz[xr] += self.sz[yr]