POJ 3517 And Then There Was One (Joseph Ring problem), poj3517
Classic Joseph Ring problem. A little deformation. Enclose N people with a ring (Number 1 ~ N), starting from the M-th individual, the reporter reports the number once every K people, and the reporter leaves the ring.
Find the number of the remaining person.
Mathematical recursive solution of Joseph's problem:
(1) the number of the first objects to be deleted is (m-1) % n.
(2) assuming that the starting Number of the second round is k, the number of n-1 is k, k + 1, k + 2, k + 3 ,....., k-3, k-2. Perform a simple ing.
K -----> 0
K + 1 ------> 1
K + 2 ------> 2
...
...
K-2 ------> N-2
This is a problem of n-1 people. If a recursive formula can be obtained from the solution of n-1 people's problems, the problem will be solved. If we already know that the number of the winner in n-1 is x and the ing relationship is used for reverse pushing, we can conclude that the number of the winner in n is (x + k) % n. K is equal to m % n. (X + k) % n <=> (x + (m % n) % n <=> (x % n + (m % n) % n <=> (x % n + m % n) % n <=> (x + m) % n
(3) The second row is deleted (m-1) % (n-1 ).
(4) assume that the starting Number of the third round is o, and the number of n-2 is o, o + 1, o + 2 ,...... o-3, o-2 .. Continue with the ing.
O -----> 0
O + 1 ------> 1
O + 2 ------> 2
...
...
O-2 ------> n-3
This is a problem for n-2 people. Assume that the final winner is y. When n-1 is selected, the winner is (y + o) % (n-1), where o is m % (n-1 ). (Y + m) % (n-1)
To get a solution for n-1 people, you only need to get the solution for n-2 people and push it down. If there is only one person, the winner is numbered 0. The recursive formula is given below:
F [1] = 0;
F [I] = (f [I-1] + m) % I; (I> 1)
Joseph problem details Stamp: http://blog.csdn.net/wuzhekai1985/article/details/6628491
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With the above recursive formula, do not rush to code it, AC ~
# Include <cstdio> # include <algorithm> using namespace std; int main () {int n, m, k; while (~ Scanf ("% d", & n, & k, & m), m | k | n) {int s = 0; for (int I = 2; I <= n-1; I ++) s = (s + k) % I; // you do not need to open an array. Printf ("% d \ n", (s + m) % n + 1);} return 0 ;}