蓝桥杯刷题--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

相关推荐

  1. --python-13-

    2024-03-18 18:00:11       44 阅读
  2. --python-28-

    2024-03-18 18:00:11       41 阅读
  3. 复习之

    2024-03-18 18:00:11       42 阅读
  4. Acwing2024

    2024-03-18 18:00:11       150 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-18 18:00:11       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-18 18:00:11       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-18 18:00:11       82 阅读
  4. Python语言-面向对象

    2024-03-18 18:00:11       91 阅读

热门阅读

  1. 手机怎么弄不同的ip地址

    2024-03-18 18:00:11       46 阅读
  2. C++——基础复习——模拟动态数组容器

    2024-03-18 18:00:11       37 阅读
  3. 【晴问算法】入门篇—贪心算法—最大组合整数

    2024-03-18 18:00:11       40 阅读
  4. 【软考】windows系统常见命令

    2024-03-18 18:00:11       44 阅读
  5. vue 函数防抖

    2024-03-18 18:00:11       46 阅读
  6. 移动端Vant2移动端组件库,相关参考地址

    2024-03-18 18:00:11       43 阅读
  7. 26.MySQL中的别名

    2024-03-18 18:00:11       38 阅读