"Children's Game (Last Remaining Numbers in the Circle)" from "The Sword Offer"

Topic description


Every year on Children's Day, teachers will prepare some small gifts to visit the children in the orphanage, and this year is the same. As a senior veteran of the teacher, HF naturally prepared some small games. Among them, there is a game like this: First, let the children form a big circle. Then, he randomly assigned a number m, and let the children numbered 0 start counting. Every time the child who shouts m-1 will go out to sing a song, and then he can choose any gift from the gift box, and will not return to the circle, starting from his next child, continue 0...m-1 Report the number.... and so on.... until the last child left, you can not perform, and get the valuable "Detective Conan" collector's edition (limited places!! ^_^). Please try to think, which child will get this gift? (Note: Children are numbered from 0 to n-1)

Code


//我的思路 是用队列。
//每次找到第(m-1)%n 的扔掉。
//最后剩下的就是答案了。
class Solution {
public:
    int LastRemaining_Solution(int n, int m)
    {    queue<int> Q;
     if (n <= 0 || m <= 0 ){
         return -1 ;
     }
     for(int i = 0;i< n ;i++){
         Q.push(i);   
        }
        while(Q.size()!= 1){
            int cent = (m - 1) % n;
            for(int j = 0;j<cent ;j++){
                Q.push(Q.front());
                Q.pop();
            }
            Q.pop();
            --n;
        }
    return Q.front();
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609393&siteId=291194637
Recommended