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

文章目录

图论基础

并查集

  • 并查集,总的来说,操作分为三步初始化(每一个节点的父亲是自己),定义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")
相关推荐
花开富贵ii2 小时前
代码随想录算法训练营四十三天|图论part01
java·数据结构·算法·深度优先·图论
yi.Ist15 小时前
图论——Djikstra最短路
数据结构·学习·算法·图论·好难
KarrySmile15 小时前
Day55--图论--107. 寻找存在的路径(卡码网)
图论·并查集·寻找存在的路径
KarrySmile1 天前
Day62--图论--97. 小明逛公园(卡码网),127. 骑士的攻击(卡码网)
图论·floyd·floyd算法·弗洛伊德算法·astar算法·小明逛公园·骑士的攻击
xnglan1 天前
蓝桥杯手算题和杂题简易做法
数据结构·数据库·c++·python·算法·职场和发展·蓝桥杯
Warren982 天前
MySQL,Redis重点面试题
java·数据库·spring boot·redis·mysql·spring·蓝桥杯
Morriser莫2 天前
图论Day2学习心得
算法·图论
KarrySmile2 天前
Day53--图论--106. 岛屿的周长(卡码网),110. 字符串接龙(卡码网),105. 有向图的完全联通(卡码网)
深度优先·图论·广度优先·广搜·岛屿的周长·字符串接龙·有向图的完全联通
zyd09152 天前
代码随想录Day50:图论(图论理论、深度搜索理论、所有可达路径、广度搜索理论)
java·数据结构·算法·leetcode·图论
啊阿狸不会拉杆2 天前
《算法导论》第 22 章 - 基本的图算法
c++·算法·排序算法·图论·拓扑学