约瑟夫斯的问题

时间:2014-02-07 23:58:25

标签: c++ josephus

我一直在使用Josephus problem(作业的另一部分),我们应该做的是提供两个变量mnm代表它开始的玩家,n代表玩家的数量。我在确定放置m变量的位置时遇到问题,以便程序在正确的播放器上启动并跳过适当数量的空格。

因此,如果m为2并且有6名玩家,它将从玩家2开始,传递给玩家3,消除玩家3并转到玩家4,传递给玩家5并消除它们,等等,直到一名球员离开。这是我希望得到的输出:

Enter M and N: 2 6

Person removed: 3
Person removed: 6
Person removed: 4
Person removed: 2
Person removed: 5

*** AND THE WINNER IS 1!! ***

相反,使用我的代码,我得到了

Person removed: 2
Person removed: 4
Person removed: 6 
Expression: list iterator not incrementable

我想到用int i = 1; i <= n; i++替换int i = m; i <= n; i++,以正确的数字开始i,但这给了我:

Player removed: 3
Player removed: 5
Player removed: 2
Player removed: 6
*** AND THE WINNER IS 4!! ***

我也知道为什么它只增加了五名球员,但我不确定m可以去哪里,以便增加正确数量的球员。任何想法/提示将不胜感激。

#include <iostream>
#include <list>

using namespace std;

int main() {
    int m, n;
    cout << "Enter M and N: ";
    cin >> m;
    cin >> n;
    list<int> players;
    for (int i = 1; i <= n; i++) {
        players.push_back(i); // adding players to the list
    }
    list<int>::iterator it = players.begin();
    while (players.size() > 1) {
        it++;
        if (it == players.end()) { // if the iterator reaches the end of the list
            it = players.begin();  // wrap around to beginning
        }
        cout << "Person removed: " << *it << endl;
        it = players.erase(it);
        if (players.size() == 1) {
            cout << "*** AND THE WINNER IS " << players.front() << "!! ***" << endl;
        }
    }

    system("pause");
    return 0;
}

0 个答案:

没有答案