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

文章目录

图论基础

并查集

  • 并查集,总的来说,操作分为三步初始化(每一个节点的父亲是自己),定义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")
相关推荐
前端小超超3 天前
capacitor配置ios应用图标不同尺寸
ios·蓝桥杯·cocoa
希望20173 天前
图论基础知识
算法·图论
行走的bug...4 天前
用图论来解决问题
算法·图论
Athenaand4 天前
代码随想录算法训练营第50天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·图论
_Coin_-5 天前
算法训练营DAY60 第十一章:图论part11
算法·图论
汉克老师5 天前
第十四届蓝桥杯青少组C++选拔赛[2023.1.15]第二部分编程题(4 、移动石子)
c++·算法·蓝桥杯·蓝桥杯c++·c++蓝桥杯
Athenaand5 天前
代码随想录算法训练营第62天 | Floyd 算法精讲、A * 算法精讲 (A star算法)、最短路算法总结篇、图论总结
算法·图论
旭意5 天前
C++微基础蓝桥杯之旅9.9-9.12
c++·算法·蓝桥杯
HAH-HAH6 天前
【蓝桥杯 2024 国 Java A】粉刷匠小蓝
c++·学习·数学·算法·职场和发展·蓝桥杯·组合数学
汉克老师6 天前
第十四届蓝桥杯青少组C++选拔赛[2023.1.15]第二部分编程题(2 、寻宝石)
c++·蓝桥杯·蓝桥杯c++·c++蓝桥杯·蓝桥杯选拔赛