Python solves the Joseph ring problem

topic:

It is said that the famous Jewish historian Josephus has the following story: After the Romans occupied Chotapat, 39 Jews hid in a cave with Josephus and his friends. 39 Jews decided that they would rather die than be caught by the enemy. , So decided a suicide method, 41 people lined up in a circle, the first person started to count, every time the third person is counted, the person must commit suicide, and then the next one recounts until everyone commits suicide Until his death. However, Josephus and his friends did not want to comply. Start with one person, pass k-2 persons (because the first person has already been passed), and kill the kth person. Then, pass the k-1 person again and kill the kth person. This process continues along the circle until finally only one person remains, and this person can continue to live.

Josephus placed his friend and himself in the 16th and 31st positions, and escaped the death game.

Similarly, the monkey chooses the king...

Using the simulation method, the time complexity is O(MK)...you will not be entangled if you use python (water)

H=[1]*41 #1代表活人,0代表死人
M=3#数到M的人自杀
K=len(H)
p=0
for i in range(K//M*M):#每次循环杀一个人,总共杀了这么多
    i=0
    while i<M:#指针p移动,经过三个活人后杀人
        if H[p%K]==1:#像这种圈,防止下标溢出就取个模。另外注意要从下一人的状态开始判断
            i+=1
        p+=1
    H[p%K-1]=0
    print(p%K,'号死了')
print()
for j in range(K):
    if H[j]==1:
        print(j+1,'号活到了最后')

The above method is suitable for writing in C (I forgot it early.
Here is another method:

H=41  #总人数
M=3  #每轮数几个数
K=[i for i in range(1,H+1)]
m=0  #报数(M)
p=0  #指针
while len(K)>H%M:#最后生还者,2(噗
    p=0
    while p<len(K):
        m+=1
        if m==M:  #数到了
            K.remove(K[p]) #死了直接删掉
            m=0
        else:
            p+=1 #如果刚刚remove过,就不用后移
print(K)

Guess you like

Origin blog.csdn.net/qq_45268474/article/details/108032048