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

文章目录

图论基础

并查集

  • 并查集,总的来说,操作分为三步初始化(每一个节点的父亲是自己),定义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")
相关推荐
汉克老师8 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(1、求和)
c++·蓝桥杯·蓝桥杯c++·c++蓝桥杯
闪电麦坤951 天前
数据结构:图的表示 (Representation of Graphs)
数据结构·算法·图论
汉克老师1 天前
第十四届蓝桥杯青少组C++国赛[2023.5.28]第二部分编程题(4、 数独填数)
c++·蓝桥杯·蓝桥杯c++·c++蓝桥杯
闻缺陷则喜何志丹1 天前
【 线段树】P12347 [蓝桥杯 2025 省 A 第二场] 栈与乘积|普及+
数据结构·c++·蓝桥杯·线段树·洛谷
BlackPercy1 天前
【图论】Graphs.jl 最小生成树算法文档
算法·图论
SuperCandyXu2 天前
洛谷 P3128 [USACO15DEC] Max Flow P -普及+/提高
c++·算法·图论·洛谷
zc.ovo2 天前
牛子图论1(二分图+连通性)
数据结构·c++·算法·深度优先·图论
古译汉书3 天前
蓝桥杯算法之基础知识(6)
数据结构·算法·蓝桥杯
ltrbless3 天前
最小生成树算法详解
算法·排序算法·图论
古译汉书3 天前
蓝桥杯算法之基础知识(4)
开发语言·python·算法·蓝桥杯