monkey king

monkey king

The subject requirements are as follows:

7-28 Monkeys choose the king (20 points)
A group of monkeys will choose a new monkey king. The selection method of the new monkey king is as follows: let N candidate monkeys form a circle and number them from 1 to N in order from a certain position. Start counting from number 1, and report from 1 to 3 in each round. All monkeys who report to 3 will exit the circle, and then start the same number from the next monkey next to it. In this continuous cycle, the last remaining monkey is selected as the monkey king. May I ask which monkey was originally elected as the Monkey King?

Input format:
Input is given in one line as a positive integer N (≤1000).

Output format:
Output the number of the elected monkey king in one line.

Input samples:
11
Output samples:
7

Problem- solving ideas:
1. After inputting the number of monkeys n, let length = n, and length represents the length of the array.
2. Use a for loop to start numbering all monkeys from 1 at the first position of the array.
3. Determine whether n is 1, if it is 1, exit the loop.
4. cnt is the counter, +1 is added after reporting a monkey, when cnt == 3, it means that the monkey with 3 is reported, then this position is assigned 0, indicating that the monkey at this position exits.
5. Every time a monkey is withdrawn, n should be -1, indicating the number of remaining monkeys.
6. Return to the judgment of 3.
7. After exiting the loop, find the remaining monkey and output its number, then break out of the for loop and end the program.

The C++ code is implemented as follows:

#include <iostream>
#include <cstdlib>
using namespace std;

int main(void)
{
    int i, cnt, n , length;
    cin >> n;
    length = n;
    int *s = (int *)malloc(sizeof(int)*length); //分配数组空间
    for(i = 0; i < length; i ++) {
        s[i] = i+1;  //按顺序从1开始输入 
    }
    i = cnt = 0;
    while(1) {
        if(n == 1) {  //如果只剩一个猴子,则跳出循环 
            break;
        }
        if(s[i] != 0) { //如果s[i] != 0,说明这个位置的猴子没有退出
            cnt ++; //则计数器+1 
        }
        if(cnt == 3) { //如果计数器加到3,即报数报到3 
            s[i] = 0; //将此位置赋0,即 
            cnt = 0; //计数器置零,重新报数 
            n --; //猴子数量-1 
        }
        i = (i+1) % length; //如果超过最长长度,则%length会重头开始 
    }
    for(int i = 0; i < length; i ++) {  //从左往右扫描,如果有一个不为0,即为猴子大王 
        if(s[i] != 0) {
            cout << s[i]; //打印此猴子 
            break; //跳出循环 
        }
    }

    return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326658979&siteId=291194637