题目:

有n个孩子站成一圈,从第一个孩子开始顺时针方向报数,报到3的人出列,下一个人继续从1报数,直到最后剩下一个孩子为止。问剩下第几个孩子。

另一种题型 -> 约瑟夫环 -> 递归算法 天道酬勤-约瑟夫环:递归算法

分析:

数到3的人退出,可暂将此人的去留状态修改。

正确代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// 写法1:
public static void main(String[] args) {
// n为在对人数,out为当前出列的人
int n=0,out=0;
Scanner sc = new Scanner(System.in);
int aa = sc.nextInt();
int[] a = new int[aa];

while(true){
for (int i = 0; i < a.length; i++) {
if(a[i]==0){
n++;
if(n==3){
a[i]=1;
n=0;
out++;
if(out==aa){
// 直接显示最后一个人
System.out.println(i+1);
}
// 显示过程中每次出列的人
// System.out.println("出列:"+(i+1));
}
}
}
if(out==aa) break;
}
}

// 写法2(ZB):
public class Yuesefu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int [] arr = new int[n];
int count = 0;
int sum = 0;

for (int i = 0; sum < arr.length -1; i++) {
if (i==arr.length) {
i = 0;
}
if (arr[i] == 0) {
count ++;
}
if (count == 3) {
arr[i] = 1;
count = 0;
sum++;
}
}

for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
System.out.println(i+1);
}
}
}
}