`
hedahai119
  • 浏览: 104671 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

约瑟夫问题的通用解决方案-猴子选大王

阅读更多

约瑟夫问题的通用解决方案,用了队列(jdk里面的)

 

题目描述:n只猴子要选大王,选举方法如下:所有猴子按 1,2 ……… n 编号并按照顺序围成一圈,从第 k 个猴子起,由1开始报数,报到m时,该猴子就跳出圈外,下一只猴子再次由1开始报数,如此循环,直到圈内剩下一只猴子时,这只猴子就是大王。

import sun.misc.Queue;


/** 
 * @author: Dahai He
 * @time: 2010-7-14 下午02:28:50
 */
public class Test{

	public static void main(String[] args) {
		//指定位置,在第几个位置进行剔除
		int M = 3;
		//指定队列的大小
        int N = 10;
        //初始化队列
        Queue q = new Queue();
        //把成员压入队列
        for (int i = 1; i <= N; i++){
            q.enqueue(i);
        }
        //对队列进行循环查找
        try {
	        while (!q.isEmpty()) {
	            for (int i = 0; i < M - 1; i++){
	            	//如果不是指定位置的元素,队列头直接去队尾
					q.enqueue(q.dequeue());
	            }
	            //把指定位置的元素提出队列
	            System.out.println(q.dequeue() + " ");
	        } 
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics