约瑟夫环问题C++实现

版权声明:个人博客网址 https://29dch.github.io/ GitHub网址 https://github.com/29DCH,欢迎大家前来交流探讨和star+fork! 转载请注明出处! https://blog.csdn.net/CowBoySoBusy/article/details/85118042

题目就不说了,学过算法或者看过一些编程思维故事的人应该都有了解这个经典的问题。这里直接看代码和运行结果。

#include <bits/stdc++.h>
using namespace std;
int n,m;
int main()
{
    while(cin>>n>>m)
    {
        int man[n]= {0};
        int count=1,i=0,pos=-1,alive=0;
        while(count<=n)
        {
            do
            {
                pos=(pos+1)%n;
                if(!man[pos])
                    i++;
                if(i==m)
                {
                    i=0;
                    break;
                }
            }
            while(1);
            man[pos]=count;
            count++;
        }
        cout<<"最初位置--约瑟夫环位置\n";
        for(i=0; i<n; i++)
        {
            cout<<i+1<<"-"<<man[i]<<" ";
            if(i!=0&&i%10==0)
                cout<<endl;
        }
        cout<<"输入剩下的人数?"<<endl;
        cin>>alive;
        alive=n-alive;
        for(i=0; i<n; i++)
        {
            if(man[i]>alive)
                cout<<"初始序号:"<<i+1<<" 约瑟夫环序号:"<<man[i]<<endl;
        }
    }
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/CowBoySoBusy/article/details/85118042