Josephus problem Intermediate (use array to simulate linked list, improve efficiency)

Source: Internet
Author: User

Description of the problem:

In the Josephus Problem 0 Foundation (using arrays). We propose one of the simplest and most straightforward solutions.

But after a careful look at the code. It is not efficient to find such a scheme, the details are now. When someone is out, traversing the array still needs to be inferred,

This is undoubtedly a futile effort. Reduced code efficiency. is especially evident in the number of people.

How to resolve:

When someone is out, consider placing the next person (not out) of the person who is currently out of the current one (not out) as the next person who is currently out.

This ensures that each addition to the counter is valid. The people who have traversed are not yet out of the game. Greatly improve the efficiency of the program. This actually uses the idea of a linked list.

Code:

 #include < Stdio.h>/*total People number*/#define ALL 100/*people leave when count to left_counter*/#define Left_counter 3/*next A Rray record the next people ' s Position*/int next[all];/*init next array*/void initnext () {int i = 0; for (i = 0; i < all ; i++) {Next[i] = (i+1)% All;}} /*print next Array*/void Printnext () {int i = 0;for (i = 0; i < all; i++) {printf ("%d", Next[i]);} printf ("\ n");} int main (void) {initnext (); int left = All;/*init Total left number*/int counter = 0;/*init Counter*/int i = 0;/*init array Index*/int prev = All-1;  /*init Prev*/while (Left > 0) {counter++;/*if counter = = Left_counter, people out, set next[prev] = next[i] Counter = 0 left--**/if (counter = = Left_counter) {left--;p rintf ("%d is out\n", i+1); counter = 0;next[prev] = next[i];p rintnext ();} /*change prev, Increase index*/prev = I;i = Next[i];} printf ("Problem finished!\n"); return 0;} 

Josephus problem Intermediate (use array to simulate linked list, improve efficiency)

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.