读书人

求一算法!解决方案

发布时间: 2012-02-04 15:43:09 作者: rapoo

求一算法!!
m个人围成一圈,从第一个人开始数,每数到第六个数退出圈外。请依次打印出退出的人的号码!(如:数到第六个人,他退出,从第七个人开始数,依次数,直到全都退出)

[解决办法]
貌似只能用循环链表做
以前是只要求最后1个人,可以用数学方法简化再用java编写
for(int i=2;i <=m;i++){
r=(r+n)%i;
}

r+1就是最后个,n是第n个退出
[解决办法]
public class Ring{
public static void main(String[] args){
int M,N;
M =20;
N =6;
boolean[] f =new boolean[M];
int r =M, n =1, i =0;
while(r> 0){
if(!f[i]){
if(n==N){
f[i] =true;
r --;
System.out.println( "第 "+(i+1)+ "号被踢 ");
n =1;
}
else n++;
}
i++;
if(i> =f.length) i=0;
}
}
}
[解决办法]
关注
[解决办法]
关注
[解决办法]
不错, 支持一下
[解决办法]
mark!
[解决办法]
Algorithm Gossip: 瑟夫(Josephus Problem)

著名太史家 Josephus有以下的故事:在人塔帕特後,39 太人Josephus及他的朋友躲到一洞中,39太人定死也不要被人到,於是定了一自方式,41人排成一圈,由第1人始,每到第3人人就必自,然後再由下一重新,直到所有人都自身亡止。

然而Josephus 和他的朋友不想遵,Josephus要他的朋友先假遵,他朋友自己安排在第16第31位置,於是逃了死亡。

public class Josephus { public static int[] arrayOfJosephus( int number, int per) { int[] man = new int[number]; for(int count = 1, i = 0, pos = -1; count <= number; count++) { do { pos = (pos+1) % number; // 理 if(man[pos] == 0) i++; if(i == per) { // 3了 i = 0; break; } } while(true); man[pos] = count; } return man; } public static void main(String[] args) { int[] man = Josephus.arrayOfJosephus(41, 3); int alive = 3; System.out.println( "琴夫排列: "); for(int i = 0; i < 41; i++) System.out.print(man[i] + " "); System.out.println( "\nL表示3存活的人要放的位置: "); for(int i = 0; i < 41; i++) { if(man[i] > alive) System.out.print( "D "); else System.out.print( "L "); if((i+1) % 5 == 0) System.out.print( " "); } System.out.println(); }}


[解决办法]
public class A {
public static void main(String[] args) {
int m = 20, sx = m;
int a[] = new int[m];
for (int i = 1; i <= m; i++)
a[i - 1] = 1;
int i = 0, lj = 1;
while (sx > 0) {
i = ++i % m;
if (a[i] != 0)
lj++;
if (lj == 6) {
a[i] = 0;
sx--;
System.out.println(i + 1);
lj = 0;
}
}
}
}

读书人网 >J2SE开发

热点推荐