关闭

C++ 计算约瑟夫环算法

标签: c++deleteiostreamincludeclass算法
1134人阅读 评论(0) 收藏 举报
分类:

#include <iostream>

using namespace std;

 

class YsfRing

{

public:

              YsfRing(int length);

              void Resolve(int firstStep);         // 求约瑟夫环

              void MoveOneStep(int& index);  // 移动一个步长

              void DisplayResult();              // 显示结果

              ~YsfRing();

private:

              int m_Length;                   // 环的长度

              int *m_Ring;                                  // 保存初始环

              int *m_Result;                  // 保存约瑟夫环的结果

};

 

YsfRing::YsfRing(int length)

{

        // 初始化环的各项数值

              m_Ring   = new int[length];

              m_Result = new int[length];

              memset(m_Ring  , 0 , sizeof(int)*length);

              memset(m_Result, 0 , sizeof(int)*length);

              m_Length = length;

              for(int i=0 ; i<m_Length;i++)

              {

                            m_Ring[i] = i+1;

              }

}

 

void YsfRing::DisplayResult()

{

        // 显示结果

              for(int i=0 ; i<m_Length;i++)

              {

                            cout<<m_Result[i]<<" ";

              }

              cout<<endl;

}

 

void YsfRing::Resolve(int firstStep)

{

        // 计算约瑟夫环

              int count = this->m_Length ;

              int resultIndex = 0;

              int index = 0 ;

              int step = firstStep;

              while( count > 0 )

              {

                // 移动相应的步长,找到下一个没有被移走的元素

                            for(int k=0;k<step;k++)

                            {

                                          MoveOneStep(index);

                            }

                // 将当前的元素保存在结果数组里面

                            m_Result[resultIndex++] = step = m_Ring[index];

                // 移走当前的元素

                            m_Ring[index] = -1;

                // 元素总数减一

                            count --;

              }

}

 

void YsfRing::MoveOneStep(int& index)

{

              do

              {

                            // 找到下一个元素

                            index ++;

                          // 如果到环尾,再跳回环头

                            if(index >= this->m_Length)

                            {

                                          index =0;

                            }

              }while(m_Ring[index] < 0 );

}

 

YsfRing::~YsfRing()

{

              delete [] m_Ring;

              delete [] m_Result;

}

 

int main()

{

              YsfRing *ring = new YsfRing(10);

              ring->Resolve(7);

              ring->DisplayResult();

              delete ring;

              return 0;

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:335899次
    • 积分:5865
    • 等级:
    • 排名:第4507名
    • 原创:248篇
    • 转载:19篇
    • 译文:0篇
    • 评论:38条
    最新评论