×

# 算法练习(43): 约瑟夫问题(1.3.37)

• 约瑟夫问题

### 题目

1.3.37 Josephus 问题。在这个古老的问题中，N 个身陷绝境的人一致同意通过以下方式减少生存人数。他们围坐成一圈（位置记作 0 到 N-1）并从第一个人开始报数，报到 M 的人会被杀死，直到最后一个人留下来。传说中 Josephus 找到了不会被杀死的位置。编写一个 Queue 的用例 Josephus，从命令行接受 N 和 M 并打印出人们被杀死的顺序（这也将显示 Josephus 在圈中的位置）。

1.3.37 Josephus problem. In the Josephus problem from antiquity, N people are in dire straits and agree to the following strategy to reduce the population. They arrange them- selves in a circle (at positions numbered from 0 to N–1) and proceed around the circle, eliminating every Mth person until only one person is left. Legend has it that Josephus figured out where to sit to avoid being eliminated. Write a Queue client Josephus that takes N and M from the command line and prints out the order in which people are eliminated (and thus would show Josephus where to sit in the circle).

``````% java Josephus 7 2
1 3 5 0 4 2 6
``````

### 分析

f[1]=0;
f[i]=(f[i-1]+m)%i; (i>1)

### 答案

``````public class Josephus {

public static void main(String[] args) {

int m = 3;
int N = 41;

Queue<Integer> queue = new Queue<Integer>();
for (int i = 0; i < N; i++)
queue.enqueue(i);

while (!queue.isEmpty()) {
for (int i = 0; i < m - 1; i++)
queue.enqueue(queue.dequeue());
StdOut.print(queue.dequeue() + " ");
}

StdOut.println();
}
}
``````

`2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36 40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 34 15 30`

Josephus.java