约瑟夫环-C++实现

#include <iostream>
using namespace std;
void main()
{
    int N, M;//N:桌上总人数;M:计数到M出局,类似游戏逢3过
    cout << "输入总人数: " << endl;
    cin >> N;
    cout << "输入计数阈值: " << endl;
    cin >> M;
    bool *a=new bool[N];
    for (int i = 0; i < N; i++)
    {
        *(a+i) = true;
    }
    int rem = N;//桌上剩余人数
    int pos = 0;//当前开始计数人的位置
    int count = 0;//当前计数大小
    //一直循环到桌上只剩一个人
    while (rem>1)
    {
        if (pos == N)
        {
            pos = 0;
        }
        if (a[pos] == true)
        {
            count++;
            if (count == M)
            {
                *(a+pos) = false;
                cout << pos << " deaded" << endl;
                --rem;
                count = 0;
            }
        }
        ++pos;
    }
    //输出桌上剩余的最后一个人(数组下标从0开始,而我们习惯从1开始,所以在输出是下标加1)
    for (int i = 0; i<N; i++){
        if (*(a+i) == true){
            cout<<"remainder: "<<i+1<<endl;//第i+1个人最后一个出局/自杀
        }
    }
    system("pause");
}

实验演示(为了便于理解,博客中的注释均为汉语,我自己的代码注释为英文):
这里写图片描述
这里写图片描述
参考的博文如下:

约瑟夫环问题

猜你喜欢

转载自blog.csdn.net/u012428169/article/details/75099799