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

//========================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;
}

你可能感兴趣的:(队列模拟解决约瑟夫环问题)