猴子选大王(约瑟夫环问题)两种解决方案

来源:互联网 发布:淘宝好吃的零食店知乎 编辑:程序博客网 时间:2024/05/29 18:33

问题:

有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;}





原创粉丝点击