蓝桥杯刷题--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
相关推荐
飞翔的佩奇11 分钟前
【完整源码+数据集+部署教程】【运动的&足球】足球比赛分析系统源码&数据集全套:改进yolo11-RFAConv
前端·python·yolo·计算机视觉·数据集·yolo11·足球比赛分析系统
智启七月27 分钟前
Dexbotic 开源深度解析:重构具身智能 VLA 研发的技术基石与实现路径
人工智能·python
beyond阿亮1 小时前
nacos支持MCP Server注册与发现
java·python·ai·nacos·mcp
感哥1 小时前
Python 装饰器
python
快秃头的码农1 小时前
vscode搭建python项目隔离的虚拟环境
ide·vscode·python
mxpan1 小时前
从 0 到 1:用 Python 对接阿里云 DashScope,轻松实现 AI 对话功能
python·ai编程
被放养的研究生2 小时前
dir()与help()
python
我的xiaodoujiao2 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest
子不语1802 小时前
深度学习(一)——基础知识:Python语言/解释器/环境/编辑器
python·学习
爱学习的爬虫3 小时前
Python实现Jenkins实现自动化执行Job
python·自动化·jenkins