import java.util.Scanner;
public class TestJosephRing {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入组成约瑟夫环的孩子数目(大于1的整数):");
int sum = input.nextInt();
System.out.print("输入约瑟夫环游戏的循环数(大于1的整数):");
int cyc = input.nextInt();
kidCircle kc = new kidCircle();
for(int i = 0;i<sum;i++){
kc.add();
}
kid k =new kid();
k=kc.first;
for(int i=0;i<sum;i++){System.out.print(k.id+" ");k=k.right;}
System.out.println();
//System.out.println(kc.count);
int index = kc.josephRing(cyc);
if(index == -1){System.out.println("围成约瑟夫环的孩子数量不够(数量应当多于一个)");}
else if(index != -1){System.out.println("约瑟夫环游戏留到最后的孩子的ID号是 "+index);}
else System.exit(-1);
}
}
class kid{
int id;
kid right;
kid left;
}
class kidCircle {
int count = 0;
kid first;
kid last;
void add(){
kid k = new kid();
if(count == 0){
k.id = 0;
first = k;
last = k;
k.right = k;
k.left = k;
}
else { k.id = count;
last.right = k;
k.left = last;
first.left = k;
k.right = first;
last = k;
}
count++;
}
void del(kid k) {
if(count == 0){System.out.println("围成约瑟夫环的孩子数量不够(数量应当多于一个)");}
if(count == 1){first = null;last = null;}
if(count > 1){
k.left.right = k.right;
k.right.left = k.left;
if(first == k){
last.right = first.right;
first.right.left = last;
first = first.right;
}
if(last == k){
last.left.right = first;
first.left = last.left;
last = last.left;
}
}
}
int josephRing(int cyc){
int num;
kid k=first;
if(count <= 1){
return -1;
}
while(count>1){
for(num=1;num<cyc;num++){
k=k.right;
}
if(num == cyc){
del(k);
kid v =new kid();
v=first;
for(int i=0;i<count-1;i++){System.out.print(v.id+" ");v=v.right;}
System.out.println();
k=k.right;
}
num = 1;
count--;
}
return first.id;
}
}