k_eckelhttp://www.mscenter.edu.cn/blog/k_eckel & http://k-eckel.cnblogs.com

Josephus问题是一个很经典的问题。对于问题的描述这里就不重复,仅给出实现的代码:

//Josephus.h

 

#ifndef _JOSEPHUS_H_

#define _JOSEPHUS_H_

 

#ifndef NULL

#define NULL 0

#endif  //~NULL

 

#include <iostream>

using namespace std;

 

class Node

{

public:

       Node():_val(-1),_next(NULL)

       {

       }

 

       Node(int val):_val(val),_next(NULL)

       {

       }

 

       Node(int val,Node* next):_val(val),_next(next)

       {

       }

 

       ~Node()

       {

              delete _next;

       }

public:

       int _val;

       Node* _next;

};

 

int Josephus(int m,int n)

{

       Node* head = new Node(1);

       head->_next = head;

       Node* h = head;

 

       for (int i = 2; i <= n; ++i)

       {

              h = (h->_next = new Node(i,head));

       }

 

       while (h != h->_next)

       {

              for (int i = 1; i < m; ++i)

              {

                     h = h->_next;

              }

 

              cout<<h->_next->_val<<" ";

              h->_next = h->_next->_next;

       }

 

       cout<<endl;

       return h->_val;

}

 

#endif //~_JOSEPHUS_H_

//main.cpp

 

#include "Josephus.h"

 

#include <iostream>

using namespace std;

 

int main(int argc,char* argv[])

{

       int n = 8;

       int m = 3;

 

       if (argc < 3)

       {

              cout<<"use the default m & n"<<endl;

       }

       else

       {

              n = atoi(argv[1]);

              m = atoi(argv[2]);

 

              cout<<"use the customised m & n: "<<m<<" & "<<n<<endl;

       }

 

       cout<<Josephus(m,n)<<endl;

 

       return 0;

}

测试程序中给出的默认的参数是83,当然你可以从命令行读入参数,不过很多人都不是很情愿到DOS界面下去运行程序并带上命令行参数,实际上你可以在VC IDE中设置命令行参数,方法为:Project->Settings->Debug->GeneralProgram Arguments中输入参数即可。

Posted on 2005-08-07 10:12  k_eckel's mindview  阅读(561)  评论(0编辑  收藏  举报