标签:结果 时间 return elf not code height 分享 复杂度
class Node: def __init__(self,value): self.value = value self.next = None def test(head,m): if not head or head.next == head or m < 2: return head # last = head # while last.next != head: # last = last.next count = 2 node = head while node.next != node: if count == m: # last = node.next node.next = node.next.next count = 1 node = node.next count += 1 head.next = None # head = node return node head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) head.next.next.next.next.next.next = Node(7) head.next.next.next.next.next.next.next = head m = 3 test(head,m)
从1人环的0计算到10人环,结果为4。转化公式:
由图知,10人环中最后入海的是4号,现由其在1人环中的对应编号0来求解。
公式:其中,m为报数值,i为第几轮。
class Node: def __init__(self,value): self.value = value self.next = None def josephus(head,m): last = head n = 1 while last.next != head: last = last.next n += 1 fn = 0 for i in range(2,n+1): fn = (fn + m) % i last = head if fn > 1: for i in range(fn-1): last = last.next pre = last.next last.next = None pre.next = pre return pre head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) head.next.next.next.next.next.next = Node(7) head.next.next.next.next.next.next.next = head m = 3 josephus(head,m)
标签:结果 时间 return elf not code height 分享 复杂度
原文地址:https://www.cnblogs.com/Lee-yl/p/9736833.html