约瑟夫问题求解:
版本一://数组实现方式,扩展名为.cpp
- #include<stdio.h>
- #include<assert.h>
- int *Joseph(int n){
- int *p;
- p=new int[n];
- for(int i=0;i<n;i++)
- p[i]=i+1;
- return p;
- }
- int NextPeople(int pre,int *WorkingArray,int number_of_people,int step){
- //计算下一个出列的人的序号
- int count=0;
- int travel=pre;
- int emptyplace=0;
- while(count<step){
- travel=(travel+1)%number_of_people;
- if(WorkingArray[travel]){
- count++;
- emptyplace=0;
- }
- else {
- emptyplace++;
- if(emptyplace==number_of_people)
- return -1;
- }
- }
- return travel; //返回出列人的序号
- }
- void CreatOutput(int *WorkingArray,int number_of_people,int step){
- //输出所有人的出列序号
- int i;
- int outnum=-1;
- for(i=0;i<number_of_people;i++){
- outnum=NextPeople(outnum,WorkingArray,number_of_people,step);
- assert(outnum>-1 && outnum<number_of_people); //断言函数
- printf("%d ",WorkingArray[outnum]);
- WorkingArray[outnum]=0;
- }
- printf("/n");
- }
- void Destory(int *WorkingArray){
- //销毁申请的数组空间
- delete[]WorkingArray;
- }
- //测试
- int main(){
- int n,m;
- int *WorkingArray;
- printf("Input number of people:");
- scanf("%d",&n);
- printf("Input step:");
- scanf("%d",&m);
- WorkingArray=Joseph(n);
- CreatOutput(WorkingArray,n,m);
- Destory(WorkingArray);
- return 0;
- }
版本二://C++版,数组实现
- #include<iostream>
- #include<cassert>
- using namespace std;
- class Joseph{
- protected:
- int number_of_people;
- int step;
- public:
- virtual void CreateOutput()=0;
- Joseph(int n,int m){
- number_of_people = n;
- step = m;
- }
- };
- class JoseArray:public Joseph{
- int *WorkingArray;
- int NextPeople(int pre);
- public:
- JoseArray(int n,int m);
- void CreateOutput();
- ~JoseArray(){delete[]WorkingArray;}
- };
- JoseArray::JoseArray(int n,int m):Joseph(n,m){
- WorkingArray=new int[n];
- for(int i=0;i<n;i++)
- WorkingArray[i]=i+1;
- }
- void JoseArray::CreateOutput(){
- int i;
- int outnum=-1;
- for(i=0;i<number_of_people;i++){
- outnum=NextPeople(outnum);
- assert(outnum>-1&&outnum<number_of_people);
- cout<<WorkingArray[outnum]<<" ";
- WorkingArray[outnum]=0;
- }
- cout<<endl;
- }
- int JoseArray::NextPeople(int pre){
- //计算下一个出列的人的序号
- int count=0;
- int travel=pre;
- int emptyplace=0;
- while(count<step){
- travel=(travel+1)%number_of_people;
- if(WorkingArray[travel]){
- count++;
- emptyplace=0;
- }
- else {
- emptyplace++;
- if(emptyplace==number_of_people)
- return -1;
- }
- }
- return travel; //返回出列人的序号
- }
- int main(){
- int n,m;
- cout<<"Input number of people:";
- cin>>n;
- cout<<"Input step:";
- cin>>m;
- JoseArray obj(n,m);
- obj.CreateOutput();
- return 0;
- }