队列模拟解决约瑟夫环问题

//========================the practice of the queue =======================//

/*************************************************
Copyright:all rights reversed
Author: Steven
Date:2010-08-25
Description: Conditions      : give you the number 1-N  in sequence.
Operation rules : move out the top  number in sequence
move the one after the top one to the end of the sequence.
task            : give the sequence of the number moved out
**************************************************/

无论是用链表实现还是用数组实现都有一个共同点:要模拟整个游戏过程,不仅程序写起

比较烦,而且时间复杂度高达O(nm),当n,m非常大(例如上百万,上千万)的时候,几乎是
没有办法在短时间内出结果的。

#include<iostream>
#include<queue>
using namespace std;
int main()
{
    int num_count =0; // the quantity of the number
    int num_separate=0;
    queue<int> num_queue; // number queue
    cout<<"length"<<endl;
    cin>>num_count;
    cout<<"num_separate"<<endl;
    cin>>num_separate;
    for(int index=0;index<num_count;index++)
    {
        num_queue.push(index+1);
    }
    while(!num_queue.empty())
    {
        if(num_queue.size()==1)
           cout<<num_queue.front()<<endl;
        num_queue.pop();
        if(num_queue.empty())
            break;
        else
        {
          for(int index=1;index<num_separate-1;index++)
          {
              num_queue.push(num_queue.front());
              num_queue.pop();
          }
        }

    }
    //cout<<"the last number is: "<<num_queue.front()<<endl;
   // num_queue.pop();
    system("pause");
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值