Joseph's ring problem-preliminary understanding + array implementation, Joseph's preliminary understanding

Source: Internet
Author: User

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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.