Topic description
Every year on Children's Day, Niu Ke will prepare some small gifts to visit the children in the orphanage, and this year is the same. As a senior veteran of Niu Ke, 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 calls 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, and continuing 0...m -1 count.... 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)
Problem solving ideas
This problem is a typical Joseph ring problem. Consider using the function f(n) to represent the last remaining number in the n numbers from 0 to n-1. The number to be removed is (m-1)%n, because the next number is Starting from the m%n number, the corresponding relationship between the number in f(n-1) and the number in f(n) is
f(n-1) f(n)
0 m%n
1 (m+1)%n
… …
n-2 (m-2)%n
The relationship between the two can be summarized: f(n) = (f(n-1) + m)% n When n=1, the remaining numbers in the circle must be 0, so the recurrence relationship is as follows:
f(n)= 0 n=1
(f(n-1)+ m)% n n>1
code
1 class Solution { 2 public: 3 int LastRemaining_Solution(int n, int m) 4 { 5 if(n<1||m<1) 6 return -1; 7 int l=0; 8 for(int i=2;i<=n;i++) 9 l=(l+m)%i; 10 return l; 11 } 12 };