思路:

模拟题目中围成一圈的场景,将n个人从1到n标号,使用队列保存每个人的编号。每次报数到m时,将队头元素出队,同时将队头元素加入队尾,模拟人围成一圈的场景。直到队列为空,说明所有人都已经出圈。

代码:

from collections import deque

n, m = map(int, input().split())
queue = deque(range(1, n + 1))

while queue:
    for i in range(m - 1):
        queue.append(queue.popleft())
    print(queue.popleft(), end=' ')
约瑟夫环问题:模拟报数出圈

原文地址: http://www.cveoy.top/t/topic/naSU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录