【python】幼儿园分班

本文介绍了一种解决二分图着色问题的算法,通过深度优先搜索(DFS)来判断一个图是否可以被分为两个独立的集合,每个集合中的节点都不与同一集合中的其他节点相连。文章首先构建了一个图的表示形式,然后使用深度优先遍历来尝试为每个节点分配颜色,如果分配过程中发现冲突,则说明该图不能被二分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://blog.youkuaiyun.com/tec_sun/article/details/99292594

二分着色问题:https://blog.youkuaiyun.com/tec_sun/article/details/99292594

【一些图的基础知识:https://www.cnblogs.com/5poi/p/7466760.html】

1. 首先需要将小朋友的请求转换成graph的格式:

num = int(input())
req = int(input())
graph = [[] for i in range(num)]

for i in range(req):
    lst = list(map(int,input().split(' ')))
    graph[lst[0]-1].append(lst[1]-1)
    graph[lst[1]-1].append(lst[0]-1)

2. 深度优先遍历:

record = [0]*num
def dfs(point,c):
    record[point] = c
    for i in graph[point]:
        if record[i] == c:
            return False
        elif record[i] == -c:
            continue
        elif record[i] == 0 and not dfs(i,-c):
            return False
    return True
flag = 1
for i in range(num):
    if record[i] == 0 and not dfs(i,1):
        flag = 0
        break
print(flag)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值