蓝桥杯刷题--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
相关推荐
千寻girling3 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook7 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风8 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风8 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习2 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员