蓝桥杯 之 图论基础+并查集

文章目录

图论基础

并查集

  • 并查集,总的来说,操作分为三步初始化(每一个节点的父亲是自己),定义union(index1,index2)函数,定义find(index)函数

并查集详细内容博客

习题

联盟X

联盟X

  • 典型的求解连通分支的题目,这个题目求解的最小连通分支
  • 我们采用并查集进行求解
python 复制代码
import os
import sys
from collections import defaultdict

# 请在此输入您的代码

# 并查集的问题
n, m = map(int, input().split())
# 记录父亲节点
parent = list(range(n + 1))
def find(index1):
    if parent[index1] != index1:
        parent[index1] = find(parent[index1])
    return parent[index1]

def union(index1, index2):
    # parent[index1] = find(parent[index2])
    parent[find(index1)] = find(index2)

for _ in range(m):
    u, v = map(int, input().split())
    union(u, v)

# 根据祖先计数,也就是同一个并查集的放在一起
store = defaultdict(int)
for i in range(1, n + 1):
    fa = find(i)
    store[fa] += 1
print(min(store.values()))

蓝桥幼儿园

蓝桥幼儿园


  • 典型的并查集模版题目
python 复制代码
import os
import sys

# 请在此输入您的代码

# 典型的并查集问题

N,M = map(int,input().split())
parent = list(range(N+1))

def find(index):
  if parent[index] != index:
    parent[index] = find(parent[index])
  return parent[index]

def union(index1,index2):
  parent[find(index1)] = find(index2)



for _ in range(M):
  op,x,y = map(int,input().split())
  if op == 1:
    union(x,y)
  if op == 2:
    if find(x)==find(y):
      print("YES")
    else:
      print("NO")
相关推荐
CoderYanger1 天前
A.每日一题:3622. 判断整除性
java·程序人生·算法·leetcode·面试·职场和发展·蓝桥杯
Chester_19993 天前
CSP202303C.LDAP
开发语言·c++·蓝桥杯·stl
lvwangshu3 天前
P6534 [COCI 2015/2016 #1] UZASTOPNI 等差树列 题解
动态规划·图论·题解·性质题
positive_zpc6 天前
进阶数据结构图——关键路径(四)
数据结构·图论·关键路径
Chester_19996 天前
CSP202206C.角色授权
开发语言·数据结构·c++·蓝桥杯
Chester_19997 天前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
云淡风轻~窗明几净7 天前
宇宙管理学猜想
算法·图论
小星星闪亮登场7 天前
图论--最小生成树(内含二分图)
数据结构·算法·图论·迭代加深·图搜索算法
positive_zpc7 天前
进阶数据结构图——最短路径(二)
数据结构·算法·图论·最短路径
positive_zpc7 天前
进阶数据结构图——最小生成树(一)
数据结构·算法·图论