AcWing 836. 合并集合
原题链接
简单
作者:
皓首不倦
,
2020-08-08 01:59:22
,
所有人可见
,
阅读 445
class MergeSet:
def __init__(self):
self.m = {}
self.__root_cnt = 0
def getRoot(self, node):
root = node
buf = []
while self.m[root] != root:
buf.append(root)
root = self.m[root]
for node in buf:
self.m[node] = root
return root
def merge(self, a, b):
for node in [a, b]:
if node not in self.m:
self.m[node] = node
self.__root_cnt += 1
root1 = self.getRoot(a)
root2 = self.getRoot(b)
if root1 != root2:
self.m[root1] = root2
self.__root_cnt -= 1
def isInSameSet(self, a, b):
for node in [a, b]:
if node not in self.m:
return False
return self.getRoot(a) == self.getRoot(b)
merge_set = MergeSet()
n, m = map(int, input().split())
for _ in range(m):
s = input()
a, b = map(int, s.split()[1:])
if s[0] =='M':
merge_set.merge(a, b)
else:
print('Yes' if merge_set.isInSameSet(a, b) else 'No')
加油加油,好厉害!