m个小朋友手拉手站成一个圈,从第k个小朋友开始报数,报到n的那个小朋友退到圈外,然后他的下一位重新报“1”。这样继续下去,直到只剩下一个小朋友,求解这个小朋友原来站什么地方。

约瑟夫环问题。

 1 package pack;
 2 import java.util.*;
 3 
 4 
 5 public class demo_2 {
 6     static int a[];
 7     public static void main(String[] args) {
 8         Scanner in=new Scanner(System.in);
 9         System.out.print("现在有M个小朋友,请输入M的值:");
10         int m=in.nextInt();
11         int a[]=new int[m+1];
12         for(int i=1;i<=m;i++)    a[i]=i;
13         System.out.print("从第k个同学开始查数,请输入k的值:");
14         int k=in.nextInt();
15         System.out.print("数到n的同学退出,请输入n的值:");
16         int n=in.nextInt();
17         int rest=m;//圈中剩余的人数
18         int pose=k;//标记,表示正在报数的人
19         int total=0;//查数查了几个,如果数到n则,从头开始来来
20         while(rest>1) {//圈中还有大于一个人。
21             if(a[pose]>0) {//如果该位置人退出,不计数
22                 total++;
23             }
24             if(total==n) {
25                 a[pose]=0;//数到n时,那么将其改为0,表示其退出
26                 total=0;
27                 rest--;
28             }
29             pose++;
30             if(pose==m+1) pose=1;
31             
32             
33         
34         }
35         for(int x:a) {
36             if(x>0)
37                 System.out.println(x);
38         }
39     
40         
41         
42         
43     }
44 }

猜你喜欢

转载自www.cnblogs.com/qq396986862/p/10732579.html