"""
https://www.lanqiao.cn/problems/1135/learning/?page=1&first_category_id=1&name=%E8%93%9D%E6%A1%A5%E5%B9%BC%E5%84%BF%E5%9B%AD
"""
# 找x的祖宗
# def Findroot(x):
# while x != p[x]:
# x = p[x]
# return x
def Findroot(x):
if x == p[x]:
return x
# 路径压缩
p[x] = Findroot(p[x])
return p[x]
# 合并x, y所在的集合
def Merge(x, y):
rootx = Findroot(x)
rooty = Findroot(y)
p[rooty] = rootx
# 查询x, y是否是同一个祖宗
def Query(x, y):
rootx = Findroot(x)
rooty = Findroot(y)
return rootx == rooty
n, q = map(int, input().split())
p = list(range(n + 1))
for _ in range(q):
op, x, y = map(int, input().split())
if op == 1:
Merge(x, y)
else:
if Query(x, y):
print("YES")
else:
print("NO")
蓝桥杯-星球大战
最新推荐文章于 2024-07-18 19:36:20 发布
本文介绍了一个基于Python的并查集数据结构,包括Findroot函数用于查找根节点,路径压缩优化效率,Merge用于合并集合,以及Query函数判断两个元素是否属于同一祖先。通过实例展示了如何在解决‘找x的祖宗’问题时使用这些方法。
摘要由CSDN通过智能技术生成