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

Source: Internet
Author: User
Tags prev

Problem Description:

In the Josephus problem primary (using arrays), we present a simple and straightforward solution.

However, after careful review of the code, it was found that the efficiency of such a scheme is not high, specifically, when someone is out, the traversal of the array still needs to be judged,

This is undoubtedly a futile effort, reducing the efficiency of the Code, especially in the number of people.

Solution:

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 increase in counter is valid and that the person who has traversed is not yet out. 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.