博客
关于我
【 POJ - 1611 】 C - The Suspects(简单并查集)求集合中元素个数
阅读量:275 次
发布时间:2019-03-01

本文共 1943 字,大约阅读时间需要 6 分钟。

为了解决这个问题,我们需要找出所有被怀疑的学生。学生0被怀疑后,所有与他同一群组的学生也会被怀疑,并且这些群组中的其他群组也会被怀疑。我们可以使用广度优先搜索(BFS)来处理这些群组,以确保所有相关的学生都被怀疑。

方法思路

  • 初始化:将学生0标记为怀疑。
  • 读取输入:读取学生数和群组数,然后读取每个群组的成员列表。
  • 建立映射:为每个学生记录他所在的所有群组。
  • BFS处理:使用队列进行BFS,处理每个群组及其成员,标记所有相关的学生为怀疑。
  • 统计结果:统计所有被怀疑的学生数量。
  • 解决代码

    import sysfrom collections import dequedef main():    while True:        n, m = map(int, sys.stdin.readline().split())        if n == 0 and m == 0:            break                groups = []        student_groups = [[] for _ in range(n)]  # student_groups[i] stores the groups that student i belongs to                for h in range(m):            parts = list(map(int, sys.stdin.readline().split()))            k = parts[0]            members = parts[1:]            groups.append(members)            for m_i in members:                student_groups[m_i].append(h)                suspicious = [False] * n        suspicious[0] = True                queue = deque()        for h in range(m):            if 0 in groups[h]:                queue.append(h)                processed = [False] * m                while queue:            current_group = queue.popleft()            if processed[current_group]:                continue            processed[current_group] = True            for member in groups[current_group]:                if not suspicious[member]:                    suspicious[member] = True                    for prime_group in student_groups[member]:                        if not processed[prime_group]:                            queue.append(prime_group)                            processed[prime_group] = True                count = sum(suspicious)        print(count)if __name__ == "__main__":    main()

    代码解释

  • 读取输入:从标准输入读取数据,直到遇到n=0且m=0时结束。
  • 初始化数据结构groups存储每个群组的成员,student_groups记录每个学生所在的群组。
  • 标记怀疑状态:使用布尔数组Suspicious记录每个学生是否被怀疑。
  • 队列初始化:将所有包含学生0的群组加入队列。
  • BFS处理:处理每个群组及其成员,标记所有相关的学生为怀疑,并将这些群组的其他群组加入队列。
  • 统计结果:计算并输出被怀疑的学生数量。
  • 该方法确保了所有相关的学生都被正确标记为怀疑,时间复杂度为O(m + n + 总成员数),在给定的约束条件下是高效的。

    转载地址:http://ctao.baihongyu.com/

    你可能感兴趣的文章
    Oracle SOA Suit Adapter
    查看>>
    Oracle Spatial GeoRaster 金字塔栅格存储
    查看>>
    Oracle spatial 周边查询SQL
    查看>>
    Oracle Spatial空间数据库建立
    查看>>
    UML— 活动图
    查看>>
    oracle sqlplus已停止工作,安装完成客户端后sqlplus报“段错误”
    查看>>
    oracle SQLserver 函数
    查看>>
    oracle sql分组(group,根据多个内容分组)在select之后from之前 再进行select查询,复杂子查询的使用
    查看>>
    UML— 时序图
    查看>>
    Oracle Statspack分析报告详解(一)
    查看>>
    oracle tirger_在Oracle中,临时表和全局临时表有什么区别?
    查看>>
    Oracle Validated Configurations 安装使用 说明
    查看>>
    oracle where 条件的执行顺序分析1
    查看>>
    oracle 中的 CONCAT,substring ,MINUS 用法
    查看>>
    Oracle 中的 decode
    查看>>
    oracle 中表一对多取多方的最新的一条数据
    查看>>
    oracle 使用 PL/SQL Developer创建表并插入单条、多条数据
    查看>>
    oracle 使用leading, use_nl, rownum调优
    查看>>
    oracle 修改字段类型方法
    查看>>
    Oracle 修改数据库表数据提交之后进行回滚
    查看>>