算法神马的,需要再加一个约瑟夫环问题

 
 
 
# 约瑟夫问题 不使用链表 纯计算方式得到:
# 第一种方法的实现,只能从头开始报数,没有办法随机指定从什么位置开始
# 如果只用YsfTest 可以用传 n 的方式 来求出第几轮被pop掉的序号

# 约瑟夫环的第一种实现:
def YsfTest(count,doom,n):
if n ==1:
temp = (count + doom - 1)%count
return temp
else:
temp = (YsfTest(count - 1,doom,n - 1)+doom)%count
return temp

def Run(count,doom):
li = []
for i in range(1,count+1):
if i == count:
res = YsfTest(count,doom,i)
print('生存人员的编号:',res)
else:
res = YsfTest(count,doom,i)
li.append(res)
return li



# 第二种实现方案:
# 首先先需要实例化一下,然后再进行函数的调用
# 一个循环链表的思路,创建一个起始的first,结尾的tail指针
# 如果从第几个孩子开始就 那么起始的first,结尾的tail指针就指向对应位置
class Child(object):
first =None
def __init__(self,no=None,pNext=None):
self.no=no
self.pNext = pNext
def addChild(self,n):
cur =None
for i in range(n):
child = Child(i + 1)
if i ==0:
self.first = child
child.pNext = self.first
cur = self.first
else:
cur.pNext = child
child.pNext = self.first
cur = cur.pNext

def showChild(self): # 检测用的 可以不写
cur = self.first
while cur.pNext != self.first:
print('当前孩子的编号:%s'%cur.no)
cur =cur.pNext
print("1当前孩子编号:%s"%cur.no)

# m为doom报的数,k是从第几个孩子开始(就把first,tail指针移动相对应位置)
def countChild(self,m,k):
tail = self.first
while tail.pNext != self.first:
tail = tail.pNext
for i in range(k-1):
tail = tail.pNext
self.first = self.first.pNext
while tail != 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('最终剩下孩子的编号:',self.first.no)
 
 
 
 
posted @ 2019-04-30 21:04  路口有雾  阅读(119)  评论(0编辑  收藏  举报