问题描述:
几个人围坐在一张圆桌周围。从编号为K的人开始报数,数到M的那个人出列;他的下一个人又从1开始报数,数到M的那个人又出列,如此反复,最后剩下的一个人胜出。
代码:
#coding=GBK
class Node():
def __init__(self,value,next=None):
self.value = value
self.next = next
def createLink(n):
if n<=0:
return False
elif n ==1:
return Node(1)
else:
root = Node(1)
tmp = root
for i in range(2,n+1):
tmp.next = Node(i)
tmp = tmp.next
tmp.next = root
return root
def showLink(root):
tmp = root
while True:
print(tmp.value)
tmp = tmp.next
if tmp ==None or tmp == root :
break
def josephus(n,k):
if k ==1 :
print("幸存者:",n)
return
root = createLink(n)
tmp = root
while True:
for i in range(k-2):
tmp = tmp.next
print("killed:",tmp.next.value)
tmp.next = tmp.next.next
tmp = tmp.next
if tmp.next == tmp:
break
print("survive:",tmp.value)
if __name__ =='__main__':
josephus(10,13)
计算结果:
killed: 3
killed: 7
killed: 2
killed: 10
killed: 1
killed: 6
killed: 8
killed: 9
killed: 4
survive: 5