约瑟夫问题


class Child(object):
first = None
def __init__(self, no=None, pNext = None):
self.no = no
self.pNext = pNext

def __str__(self):
return self.no

def add(self, n = 1000):
cur = None
for i in range(n):
child = Child(i+1)
if i==0:
self.first = child
self.first.pNext = child
cur = self.first
else:
cur.pNext = child
child.pNext = self.first
cur = cur.pNext

def show(self):
cur = self.first
while cur.pNext != self.first:
print('小孩的编号是%s' % cur.no)
cur = cur.pNext
print('小孩的编号是%s' % cur.no)

# k = 2 m = 3000
def countChild(self, m, k):
tail = self.first

while tail.pNext != self.first:
tail = tail.pNext

# 当退出循环的时候, 已经在first的后面

for i in range(k - 1):
self.first = self.first.pNext
tail = tail.pNext

# 数两下, tail 和 first走一次
# 数三下, tail 和 first走两次
while self.first.pNext != self.first:
for i in range(m - 1):
tail = tail.pNext
self.first = self.first.pNext

self.first = self.first.pNext
tail.pNext = self.first

print('留在圈中的小孩是%s' % tail.no)


c = Child()
c.add()
c.show()
c.countChild(3, 2)
posted @ 2019-01-29 09:44  不沉之月  阅读(81)  评论(0编辑  收藏  举报