当前位置:   article > 正文

蓝桥杯刷题--python-13-并查集

蓝桥杯刷题--python-13-并查集

模板:

# init
p = [i for i in range(N + 1)]
def union(p, i, j):
    p1 = parent(p, i)
    p2 = parent(p, j)
    p[p1] = p2


def parent(p, i):
    root = i
    while p[root] != root:
        root = p[root]
    while p[i] != i:
        x = i;
        i = p[i];
        p[x] = root
    return root

1249. 亲戚 - AcWing题库 

# init

def union(p, i, j):
    p1 = parent(p, i)
    p2 = parent(p, j)
    p[p1] = p2


def parent(p, i):
    root = i
    while p[root] != root:
        root = p[root]
    while p[i] != i:
        x = i;
        i = p[i];
        p[x] = root
    return root


# 创建并查集
N, M = map(int, input().split())
#
p = [i for i in range(N + 1)]

while (M):
    a, b = map(int, input().split())
    union(p, a, b)
    M -= 1
Q = int(input())
while (Q):
    c, d = map(int, input().split())
    if (parent(p, c) == parent(p, d)):
        print("Yes")
    else:
        print("No")

    Q -= 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/286365
推荐阅读
相关标签
  

闽ICP备14008679号