约瑟夫(josephus)环算法实现

本文探讨了经典的约瑟夫(Josephus)环算法,通过实例展示了当6个小孩按照每2个出局的规则进行游戏时,最终留下的是第5个小孩。文章提供了相关的代码实现,详细解释了算法过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    约瑟夫(josephus)环是这样的:假设有n个小孩坐成一个环,假如从第一个小孩开始数,如果数到m个小孩,则该小该离开,问最后留下的小孩是第几个小孩?例如:总共有6个小孩,围成一圈,从第一个小孩开始,每次数2个小孩,则游戏情况如下:
    小孩序号:1,2,3,4,5,6
    离开小孩序号:2,4,6,3,1
最后获胜小孩序号:5

代码:

 

//  josephus.cpp : 定义控制台应用程序的入口点。
//

#include 
" stdafx.h "
#include 
" iostream "

using   namespace  std;
int  _tmain( int  argc, _TCHAR *  argv[])
{
    
int  peopleNumber;
    cout
<< " 输入环中的人数: " ;
    cin 
>> peopleNumber;
    
int *  people  =   new   int [peopleNumber];
    
int *  people_flag  =   new   int [peopleNumber];

    cout
<< " 初始化...... " << endl;
    
for ( int  i  =   0  ; i  <  peopleNumber ; i ++ )
        {
            people[i] 
=  i;
            people_flag[i] 
=   0 ;
        }

    
int  interval;
    cout
<< " 输入淘汰者要读的数字 " ;
    cin 
>>  interval;

    
int  count  =   0 ;
    
int  people_least  =  peopleNumber;
    
do
    {
    
for ( int  i  =   0 ; i  <  peopleNumber; i ++ )
        {
            
if (people_flag[i]  ==   0   &&  count  ==  interval)
                {
                    cout 
<<   " "   <<  peopleNumber  -  people_least + 1   <<   " 轮序号是 "   <<  people[i]  <<   " 的人被踢出环 "   <<  endl;
                    people_flag[i] 
=   1 ;
                    count 
=   0 ;
                    people_least 
-- ;
                }
            
if (people_flag[i]  ==   0   &&  count  !=  interval)
                {
                    count 
++ ;
                }
        }
    }
while (people_least  !=   1 );
    
    
for ( int  i  =   0  ; i  <  peopleNumber ; i ++ )
        {
            
if (people_flag[i]  ==   0 )
                cout
<< " 现在还剩序号是 " << people[i] << " 的人 " << endl;
        }

    getchar();
    getchar();
    
return   0 ;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值