17 Monkeys in a circle, from some beginning to count 1-2-3-1-2-3-...... Reported "3" of the monkeys were eliminated, the game has been carried out into the circle only a monkey It is the Monkey King.
method One:
Tip: Use an array to record whether the monkey is in the circle: "1" in the circle, not in the circle as "0". It also simulates the count-off process by accumulating the values of the array elements, thus reducing the operation of the monkey in the circle.
The C + + code is as follows:
#include <iostream>#include <vector>using namespace STD;Const intN = -;//print n the state of a monkey ("1" means in the circle, "0" means not in the circle)voidPrintvec (Const vector<int>&V) { for( vector<int>:: Const_iterator it = V.begin (); It! = V.end (); ++it) {cout<<*it<<"'; }cout<<endl;}intMonkeyking ( vector<int>V) {//n Record How many more monkeys are in the circle . intn = n;intK =0;intI while(N >1) { for(i=0; i<n;++i) {k + = V[i];if(k = =3) {V[i] =0; Printvec (v); K =0; --n; } } }//The last monkey subscript is 1 for(intI=0; i<n;++i) {if(1= = V[i])returni+1; }}intMain () { vector<int>V (N,1);cout<<"Monkey King is the first"<<monkeyking (v) <<"only."<<endl;return 0;}
Operation Result:
Method Two:
The disadvantage of method one is to scan all the monkeys that have been out of the loop each time, the time efficiency is lower. If you use an array element to store the next marker in the inner circle, you can easily find the next monkey in the circle. When a monkey's next monkey is himself, there is only one monkey in the circle, it is waiting for the king.
C + + code:
#include <iostream>#include <vector>using namespace STD;Const intN = -;intMain () { vector<int>V (N,0); for(intI=0; i<n-1; ++i) {V[i] = i+1; }intTest =0;intLast while(Test! = V[test]) { for(intI=0;i<3; ++i) {last = V[test]; Test = V[last];cout<<"section"<<test+1<<"only monkey 3"<<endl; V[last] = V[test]; Test = V[test]; } }cout<<"Monkey King is the first"<<test+1<<"only."<<endl;return 0;}
Operation Result:
Monkey Choice King (two ways)