class UF:
def __init__(self, count):
self.count = count
self.parent = [i for i in range(count)]
self.size = [1]*count
def find(self,x):
if x==self.parent[x]:
return x
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,p,q):
rootp = self.find(p)
rootq = self.find(q)
if rootp==rootq:
return
if self.size[rootp]>self.size[rootq]:
self.parent[rootq]=rootp
self.size[rootp]+=self.size[rootq]
else:
self.parent[rootp]=rootq
self.size[rootq]+=self.size[rootp]
self.count-=1
def connected(self,q,p):
rootp = self.find(p)
rootq = self.find(q)
return rootp==rootq
并查集模板
最新推荐文章于 2022-10-10 14:42:24 发布