import java.io.*;
public class Josephus {
public Josephus() {
}
public static void main(String[] args) {
String s1;
int n = 0;
int i = 1;
int S = 1; //从第S人起
int D = 0; //查数
int divisor = 1; int countU0 = 0; //非零元个数
int count0 = 0; //零元个数
System.out.println("请输入队列总人数:");
try{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s1=in.readLine();
n=Integer.valueOf(s1);
}catch(IOException e){}
int N[] = new int[n+1];
int count = N.length-1; //总人数
System.out.println("请输入每次要数的人数:");
try{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s1=in.readLine();
D=Integer.valueOf(s1);
}catch(IOException e){}
System.out.println("请输入队列起始查的编号:");
try{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s1=in.readLine();
S=Integer.valueOf(s1);
}catch(IOException e){}
System.out.print(D+" 约瑟夫环队列顺序:");
for( ;i <= count/2; i++)
{
N[i] = i; //犯人编号,N[1...] = 1,2,3,4,5
}
//查数,遇到不为0的数则加1
i = S;
while(true)
{
if(count0 == count/2)
{
System.out.println("");
System.out.println("最后的生还者是:"+divisor +"号犯人");
break;
}
//避免到达数组元素N[0]
if(i % count == 0)
{divisor = count;}
else
{divisor = i % count;}
//开始数数
if(N[divisor] != 0) //当前人不是已出列的
{
countU0 ++;
}
if(countU0 == D) //已经查到应该出列的人
{
N[divisor] = 0; //让此人出列
countU0 = 0; //重新计数
count0 ++; //出列人数加1
System.out.print(divisor + " ");
}
i ++;
if(i - 1 == count) i = 1; //当查至人数时,从新开始计数
}
}
}
public class Josephus {
public Josephus() {
}
public static void main(String[] args) {
String s1;
int n = 0;
int i = 1;
int S = 1; //从第S人起
int D = 0; //查数
int divisor = 1; int countU0 = 0; //非零元个数
int count0 = 0; //零元个数
System.out.println("请输入队列总人数:");
try{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s1=in.readLine();
n=Integer.valueOf(s1);
}catch(IOException e){}
int N[] = new int[n+1];
int count = N.length-1; //总人数
System.out.println("请输入每次要数的人数:");
try{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s1=in.readLine();
D=Integer.valueOf(s1);
}catch(IOException e){}
System.out.println("请输入队列起始查的编号:");
try{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s1=in.readLine();
S=Integer.valueOf(s1);
}catch(IOException e){}
System.out.print(D+" 约瑟夫环队列顺序:");
for( ;i <= count/2; i++)
{
N[i] = i; //犯人编号,N[1...] = 1,2,3,4,5
}
//查数,遇到不为0的数则加1
i = S;
while(true)
{
if(count0 == count/2)
{
System.out.println("");
System.out.println("最后的生还者是:"+divisor +"号犯人");
break;
}
//避免到达数组元素N[0]
if(i % count == 0)
{divisor = count;}
else
{divisor = i % count;}
//开始数数
if(N[divisor] != 0) //当前人不是已出列的
{
countU0 ++;
}
if(countU0 == D) //已经查到应该出列的人
{
N[divisor] = 0; //让此人出列
countU0 = 0; //重新计数
count0 ++; //出列人数加1
System.out.print(divisor + " ");
}
i ++;
if(i - 1 == count) i = 1; //当查至人数时,从新开始计数
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货