有N我的圍成一圈,第一我的從1開始報數,報到M的人出列,求最後一個出列的人。
這是一個約瑟夫環問題,下面給出了java實現的例子:
package com.juziku;import java.util.Arrays;/*** n我的圍成一圈,報到m的人出列* @author sunlightcs* 2011-3-8* http://hi.juziku.com/sunlightcs/*/public class Queue { public static void main(String[] args) { queue(10, 3); } /** * 最後出隊的人 * @param total 總的人數 * @param num 第幾號出隊 */ public static void queue(int total, int num){ //定義一個數組,true表示沒有出隊列的,false表示已經出隊列的 boolean []arr = new boolean[total]; Arrays.fill(arr, true); //移動變量,如:1 2 3 1 2 3 1 2 int next = 1; //數組下標 int index = 0; //剩下的人數 int count = total; //若是剩下的人數爲1人時,中止報數 while(count>1){ if(arr[index] == true){ if(next == 3){ arr[index] = false; //剩下的人數減1 --count; //移動變量復位,從1開始報數 next = 1; System.out.println("依次出列的人爲:"+(index+1)); }else{ ++next; } } ++index; if(index == total){ //數組下標復位,從0開始新重遍歷 index = 0; } } for(int i=0; i<total; i++){ if(arr[i] == true){ System.out.println("最後出列的人爲:"+(i+1)); } } }}
全文請訪問:[url=http://www.renren.io]人人編程[/url]