First of all see this problem in the brain immediately jump out of the list. Then continue to look at home analysis said, the chain table method time complexity of O (N*k), will certainly tle, I realized that it is a simple mind t^t.
Look at home analysis not how to understand, later found that this article oneself understand easier (...) ) share a little bit of ~http://blog.csdn.net/chenguolinblog/article/details/8873444
Problem description: N Person (number 0~ (n-1)), starting from 0 count, reporting (M-1) exit, the remainder continues to count off from 0. The winner's number.
The number 0~ (n-1) is meaningful because it is modulo n, so it is better to operate with 0-(N-1)
We know the first person (the number must be (m-1) mod n) after the dequeue, the remaining n-1 individuals make up a new Joseph ring (starting with the person numbered k=m mod n):
K k+1 k+2 n-2,n-1,0,1,2,... k-2
And at the beginning of the K is reported 0.
Now let's do a conversion of their numbers:
K--0
K+1-1
K+2-2
...
...
K-2-N-2
After the transformation has completely become the (n-1) personal count of the sub-problem, if we know the solution of this sub-problem: for example, X is the final winner, then according to the above table to turn this x back is not exactly the solution of n personal situation?! The formula to change back is very simple, I believe everyone can push out: X ' = (x+k) mod n;
So as long as we repeat this process, we can get the first person's number, because this person's final number is 0 (he alone):0-> (0+k)%2-> ((0+k)%2+k)%3->
f[n]= (f[n-1]+k)%n,f[1]=0; F[i] Indicates that there is an I person when the last Victor number
==========================================
Note that this idea is applicable to the classical Joseph ring problem.
==========================================
The following will be deformed ...
Now the problem is starting with M, which is the first (m-1) number of people going out. And then just like the normal Joseph Ring. So as long as we f[n]= (f[n-1]+m)%n alone counted on the line. Other f[i]= (f[i-1]+k)%i; (1<i<n);
The code is as follows:
1#include <iostream>2#include <cstdio>3#include <cstdlib>4#include <cstring>5 using namespacestd;6 Const intMAXN =10005;7 intF[MAXN];8 intMain ()9 {Ten intN, K, M, step, CNT; One while(~SCANF ("%d%d%d", &n, &k, &m)) A { - if(!n &&!k &&!m) Break; -f[1] =0; the for(inti =2; I < n; i++) - { -F[i] = (f[i-1]+K)%i; - } + intAns = (f[n-1]+M)%N; -printf"%d\n", ans+1); + } A return 0; at}
"Joseph Ring variant" UVa 1394-and then there is one