7-28 Monkey King (20 points) (queue)

A group of monkeys have to choose a new monkey king. The method of selecting the new monkey king is to make N candidate monkeys form a circle and number them sequentially from a certain position from 1 to N. Counting starts from the first number, and every round from 1 to 3, every monkey who reports to 3 will exit the circle, and then start the same counting from the next monkey. In such a continuous cycle, the last remaining monkey is selected as the monkey king. Excuse me, which monkey was elected as the Monkey King?

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

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

Input sample:

11

Sample output:

7

With a queue, if there are only two numbers left, then the second number is left. If it is greater than or equal to 3, the first two will be enqueued in sequence, and the subsequent counts will be continued, and the third will be discarded directly. Through the counting process, you can understand how the queue works. It's actually the Joseph ring problem
#include <iostream>
#include <queue>
using namespace std;

int main() {
    
    
    queue<int> qe;
    int n;
    cin >> n;
    if (n == 1) {
    
    //如果只有一个,那么肯定就是它了呗,测试点1
        cout << 1;
        return 0;
    }
    for (int i = 1; i <= n; i++) {
    
    
        qe.push(i);
    }
    while (true && !qe.empty()) {
    
    
        if (qe.size() == 2) {
    
    //只有两个数了,可以判断结果了
            qe.pop();
            cout << qe.front();
            return 0;
        } else if (qe.size() >= 3) {
    
    
            qe.push(qe.front());//报1的入队
            qe.pop();
            qe.push(qe.front());//报2的入队
            qe.pop();
            qe.pop();//报3的直接出队舍弃
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45845039/article/details/112338585