約瑟夫環(數組模擬實現)

#include <stdio.h>
#include <stdlib.h>

const int MAX_NUM = 300;
int aLoop[MAX_NUM + 10];

int main(void)
{
	int i,n,m;
	while(1)
	{
		scanf("%d%d",&n,&m);//n總人數,m要出圈的猴子數
		if(n == 0)
			break;
		for(i = 0; i < n; i++)
			aLoop[i] = i + 1;
		int nPtr = 0;
		for(i = 0; i < n; i++)//每次循環將1只猴子趕出圈
		{
			int nCounted = 0;//記錄本輪數到的猴子數目;
			while(nCounted < m)
			{
				//一直數到第m個猴子
				while(aLoop[nPtr] == 0)//跳過已出圈的猴子
					nPtr = (nPtr + 1)%n;//到下一個位置
				nCounted++;//數到一隻猴子
				nPtr = (nPtr + 1)%n;//指定下一個位置
			}
			nPtr--;//要回退一個位置
			if(nPtr < 0)
				nPtr = n - 1;//最後一個出圈的猴子
			if(i == n - 1)
				printf("%d\n",aLoop[nPtr]);
			aLoop[nPtr] = 0;//猴子出圈;
		}
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章