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

文章目录

图论基础

并查集

  • 并查集,总的来说,操作分为三步初始化(每一个节点的父亲是自己),定义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")
相关推荐
珂朵莉MM7 小时前
2024 睿抗机器人开发者大赛CAIP-编程技能赛-专科组(国赛)解题报告 | 珂学家
开发语言·人工智能·算法·leetcode·职场和发展·深度优先·图论
callJJ8 小时前
Bellman - Ford 算法与 SPFA 算法求解最短路径问题 ——从零开始的图论讲解(4)
数据结构·算法·蓝桥杯·图论·单源最短路径·bellman- ford算法
a东方青16 小时前
蓝桥杯 2024 C++国 B最小字符串
c++·职场和发展·蓝桥杯
pystraf1 天前
模板分享:网络最小费用流
c++·算法·图论·网络流
啊我不会诶2 天前
CF每日5题(1300-1500)
算法·深度优先·图论
冲帕Chompa2 天前
图论拓扑排序
图论
freyazzr2 天前
Leetcode刷题 | Day63_图论08_拓扑排序
数据结构·c++·算法·leetcode·图论
咚咚轩2 天前
蓝桥杯12届国B 纯质数
蓝桥杯
Nobkins2 天前
2023CCPC河南省赛暨河南邀请赛个人补题ABEFGHK
开发语言·数据结构·c++·算法·图论
qystca2 天前
P8803 [蓝桥杯 2022 国 B] 费用报销
蓝桥杯