蓝桥杯刷题--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
相关推荐
ZhengEnCi1 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽3 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187914 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L20 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅20 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅20 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L20 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅21 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L21 小时前
python的类&继承
python