猴子選大王(約瑟夫環問題)兩種解決方案
阿新 • • 發佈:2019-01-07
問題:
有M只猴子圍成一圈,按序每隻從1到M中的編號,打算從中選出一個大王;經過協商,決定出選大王的規則:從第一個開始迴圈報數,數到N的猴子出圈,最後剩下來的就是大王。要求:從鍵盤輸入M、N,程式設計計算哪一個編號的猴子成為大王
示例:
比如有5只猴子,從1到3報數,則選大王的步驟如下: 第一次報數:1->2->3 //3淘汰出圈 第二次報數:4->5->1 //1淘汰出圈 第三次報數:2->4->5 //5淘汰出圈 第四次報數: 2->4->2 //2淘汰出圈 4號稱王。 // monkey.cpp : Defines the entry point for the console application. // 方案一:;利用陣列
#include "stdafx.h" #include <iostream> using namespace std; int findMonkeyKing(int m,int n){ int* a= new int[m]; //將猴子按從1到m編號 for(int i=1;i<=m;i++){ a[i-1]=i; } int start=0;//第一次報數從第一隻猴子開始 int count=n;//記錄報數的次數 int len=m;//記錄陣列的大小 while(m>1){ while(count>1){ if(a[start]>0){ count--; if((start+1)<len) start++; else start=0; } else { if(start+1<len) start++; else start=0; } } //找到要淘汰出圈的猴子 while(a[start]==0){ if(start+1<len) start++; else start=0; } //cout<<a[start]<<"_"<<start<<endl; a[start]=0;//將該猴子淘汰。 //找到下一個開始從1報數的猴子 while(a[start]==0){ if(start+1<len) start++; else start=0; } //cout<<a[start]<<"_"<<start<<endl; count=n;//為下次迴圈做準備 m--; } //找到陣列中僅存的值不為0的陣列元素即為所選猴子大王 int j=0; while(a[j++]==0); return a[j-1];//這個地方要小心,要後退一步 } int main(int argc, char* argv[]) { int m,n; cout<<"請輸入猴子的總只數m:"; cin>>m; cout<<endl; cout<<"請輸入報數的次數n:"; cin>>n; cout<<endl; int monkeyKing=findMonkeyKing(m,n); cout<<"第"<<monkeyKing<<"號猴子是大王"<<endl; return 0; }