For a long time did not look at the problem of the algorithm, today waste a lot of strength, again exclamation: to want to learn the algorithm will often practice, there is no shortcut to go. Nonsense not much to say, as follows:
Problem Description: There are m individuals, surrounded by a ring, numbered 0, 1, 2, 3 、、、 m-1, starting from the first person to cycle off, assuming a number to N of the person out, and then from the next person continue to count, Count to n out, in this cycle, the last man to win, the winner's number.
The analysis is as follows:
Set m for the number of N for the number of the number k for starting from the first few people
The first sequence is recorded as a.
0 1 2 3 4 5 6 7 8 9 、、、 n%m k 、、、 m-2 m-1
Assuming that a person has been out for the first time, the number must be n%m-1 (minus 1 because it starts from zero). K=n%m, the number of columns after the first
0 1 2 3 4 5 6 7 8 9 、、、 k 、、、 m-2 m-1
The second time starting from the K number then you can make up a new series, which is counted as the array b
K->0
K+1->1
K+2->2
K+3->3
、
、
、
K-3->m-3
K-2->m-2
If we know that the final winner of Series B is the number x, what is the number of x in the original sequence a? It is easy to figure out: (x+k)%m, and K=n%m, replaced by (x+n%m)%m= (x+n)%m, (x+n)%m for the winner of column A. So how about X, we can ask for the series C, and so on the analogy. Until there is only one person, the winner's number must be 0.
Suppose F (Y) is the winner: then there is
F (1) = 0;
F (2) = (f (1) +n)%2;
F (Y) = (f (y-1) +n)%y; (formula) y the number of people n is the number of
The following is a programmatic implementation, replacing F (y) with number y replaced by i
/*********************************************************************** **m Total number, the number is 0~m-1 N for the number of numbers * * Successful return sequence number 1~m, Failed to return-1 ***********************************************************************/ intWinnerintMintN) {inti; intNumber ; if(M <=0|| N <=0) { return-1; } Number=0;/*when there is only one person, the ring numbered 0*/ for(i =2; I <= m;i++) {/*Cycle m-1 time there will be one left.*/ Number= (number + n% i)% i;/*This writing is easy to understand, or (number+n)%i*/ } returnNumber +1;/*The program is numbered from 0 and should be returned +1*/ }
Analysis of Joseph Ring problem