AcWing 836. 合并集合 python
原题链接
简单
作者:
申侠
,
2020-10-23 17:30:23
,
所有人可见
,
阅读 245
# Disjoint Set Union
class DSU():
def __init__(self,n):
self.lt = [i for i in range(n+1)]
def find(self,a):
lt = self.lt
if lt[a] != a:
lt[a] = self.find(lt[a]) # 路径压缩
return lt[a]
def merge(self, a, b):
self.lt[self.find(a)] = self.find(b)
def query(self,a,b):
return 'No' if self.find(a) != self.find(b) else 'Yes'
n,m = map(int , input().split(' '))
dsu = DSU(n)
for _ in range(m):
cmd, a, b = map(str , input().split(' '))
a = int(a)
b = int(b)
if cmd == 'Q' :
print(dsu.query(a,b) )
else:
dsu.merge(a,b)