package huawei;
import java.util.Scanner;
/**
* 约瑟夫环问题:
* 已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。
* 从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;
* 依此规律重复下去,直到圆桌周围的人全部出列。
*
* 方法一:通过数组实现:巧妙之处是利用下标index一直增加且对n求余来实现循环计数
*
* @author USER
*
*/
public class Josephus {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();//数到m,m可以大于n
int k = in.nextInt();
method(n,m,k);
}
private static void method(int n, int m, int k) {
int[] a = new int[n];
int len = n;
for (int i = 0; i < len; i++) {
a[i] = i+1;
}
int count = 1;//计数
int index = k-1;//每次计数的下标,一直增加,因为是数组下标,所以要减1
while (len > 0) {
if (a[index%n] > 0) {//巧妙:利用index对n求余
if (count == m) {
System.out.print(a[index%n]+" ");
a[index%n] = -1;
index++;
count = 1;
len--;
}else {
count++;
index++;
}
}else {//遇到已经出列的位置,跳过,但是index始终增加。
index++;
}
}
}
}
方法二:
package huawei;
import java.util.Scanner;
/**
* 方法二:通过链表循环实现:操作简单,容易实现
* @author USER
*
*/
class Node{
int num;//编号
Node next;//指针结点
Node(int num){
this.num = num;
}
}
public class JosephusLink {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
//建立循环链表
Node header = new Node(1);//头结点
Node current = header;
for (int i = 2; i <= n; i++) {
current.next = new Node(i);
current = current.next;
}
current.next = header;//此时current结点为尾结点,指向头结点
//让current结点为第k个编号结点的前一个结点
for (int i = 1; i < k; i++) {
current = current.next;
}
//实现出列操作
while (current != current.next) {
for (int i = 1; i < m; i++) {
current = current.next;
}
System.out.print(current.next.num+" ");
current.next = current.next.next;//结点出列
}
System.out.println(current.next.num);
}
}