Joseph's ring problem-preliminary understanding + array implementation, Joseph's preliminary understanding
Joseph's ring problem-preliminary understanding + Array Implementation
The first contact with Joseph's ring problem is still in the C language book. The specific questions are as follows: n people sit in a circle, select a person (for example, 1st), and report data from 1, the person who counts to m in a clockwise direction is eliminated, and then the next person continues to report the number from 1, and then the person who counts to m is eliminated. Repeat the above process and output the remaining person.
Solution:
Step 1: Create an array with a length of n;
Step 2: The deleted location number is I = (I + m-1) % n. Why? Because the first personnel I = 0, and then I add an m-1 to delete another person, think of the array as a "ring.
Step 3: After I is deleted, the array elements following it move forward;
Step 4: When I is the last number in the array, after deletion, the new I cannot be moved (there is no number next), So I = 0;
The code implementation is as follows:
# Include <iostream> using namespace std; int main () {int m, n; cin> n> m; int * p = new int [n]; int I; for (I = 0; I <n; I ++) // initialize {p [I] = I + 1;} while (n> 1) {I = (I + m-1) % n; // locate the location to be deleted, cout <p [I] <"deleted" <endl; for (int j = I + 1; j <n; j ++) // only j = I + 1 {p [j-1] = p [j];} n --; if (I = n) // if the last element is deleted, You need to reset I to 0 {I = 0 ;}} cout <"The rest is" <p [I] <endl; delete [] p; return 0 ;}
The result is as follows:
In addition, you can also use linked lists, queues, stacks, and Other implementations, and write them later.