問題描寫敘述:數組
在《josephus Problem 0基礎(使用數組)》中。咱們提出了一種最簡單直接的解決方式。spa
但是,細緻審視代碼以後。發現此種方案的效率並不高,詳細體現在。當有人出局時,遍歷數組仍需要對其進行推斷,code
這無疑作了無用功。減小了代碼效率。在人數多時尤爲明顯。blog
解決方式:ip
當有人出局時,考慮將當前出局的人的前一我的(未出局)的下一我的置爲當前出局的下一我的(未出局)。it
這樣,便確保了每次對counter的添加都是有效的。遍歷到的人都是尚未出局的。大大提高了程序的效率。這事實上運用了鏈表的思想。io
代碼:class
#include <stdio.h> /*total people number*/ #define ALL 100 /*people leave when count to left_counter*/ #define left_counter 3 /*next Array 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--; printf("%d is out\n", i+1); counter = 0; next[prev] = next[i]; printNext(); } /*change prev, increase index*/ prev = i; i = next[i]; } printf("problem finished!\n"); return 0; }