約瑟夫問題

/*
 * 說有15個教徒和15個非教徒在海上遇難,必須將一半的人投入海中,其餘的人才能倖免於難。於是他們想了一個辦法:30個人圍成一圈,從第一個人開始報數,每數到第九個人的時候將之投入大海,如此循環直到剩下15個人爲止。問:怎樣的排法可以使被投入大海的都是非教徒?
 *
 * StoryMonster    2016/7/14
 */
#include <iostream>

using namespace std;

enum {BELIEVER=0,NONBELIEVER};
int main()
{
    unsigned short people[30] = {BELIEVER};
    unsigned short surviver = 30;
    unsigned short index = 0;
    while(surviver > 15)
    {
        unsigned short count = 0;
        while(1)
        {
            if(people[index] == BELIEVER)
            {
                count++;
                if(count == 9) break;
            }
            index++;
            if(index == 30) index = 0;
        }
        people[index] = NONBELIEVER;
        surviver--;
    }
    for(index=0;index<30;index++)
    {
        if(people[index] == BELIEVER)
            cout<<"BELIEVER  ";
        else cout<<"NONBELIEVER  ";
    }
    cout<<endl;
    return 0;
}
發佈了65 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章