[Offer] to prove safety of the children's game (circle last remaining number)

Topic links: Child's Play (circle last remaining number)


Meaning of the title: the annual Children's Day, cow-off will prepare some small gifts to visit the orphanage children, this year is also true. As an experienced veteran off HF cattle, naturally we prepared some games. Among them, there is a game like this: First, let the children surrounded by a large circle. He then randomly assigned a number m, so that number of children 0 gettin number. Cried every time m-1 the children sing a song to be out of the line, then any of the gift box in choosing a gift, and not return to the circle, starting with his next child, continue 0 ... m -1 number of packets .... go on .... until the last remaining child, you can not perform, and get the cattle off the rare "Detective Conan" Collector's Edition (limited places oh !! ^ _ ^). You want to try next, which the children will get the gifts it? (NOTE: The number of children is from 0 to n-1)

 
If there are no children, please return -1

 

Solution: Joseph Central ,, classic problem. .

 

Code:

 1 class Solution {
 2 public:
 3     int LastRemaining_Solution(int n, int m){
 4         if(n < 1 || m < 1)  return -1;
 5 
 6         int ans = 0;
 7         for(int i = 2; i <= n ;i++){
 8             ans = (ans+m)%i;
 9         }
10         return ans;
11     }
12 };

 

Guess you like

Origin www.cnblogs.com/Asumi/p/12417061.html