從面向結構到面向對象-----josephus問題(方法三:結構化方法的實現)



<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 josephus問題:幾個小孩圍成一圈,從任意一個小孩間隔m順時針方向數起,每數到第m個小孩時,該小孩就離開。最後一個剩下的就爲勝利者。第幾個爲勝利者?



//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//方法三:結構化方法的實現
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <iostream.h>
#include <iomanip.h>

struct Jose
{
  int code;
  Jose *next;
};

int n;
int begin;
int m;
Jose *pivot,*pCur;

int assign();
void initial(Jose *pJose);
void count(int m);
void process();

void main()
{
  if(!assign())
  {
    cout<<"The program failed."
        <<endl;
    return;
  }

  Jose *pJose=new Jose[n];
  initial(pJose);
  count(begin);
  process();

  cout<<endl
      <<"the winner is:"
      <<pCur->code
      <<endl;

  delete []pJose;
}

int assign()
{
  int number,start,count;
  cout<<"please input the number,start,count:"
      <<endl;
  cin>>number>>start>>count;

  if(number<3)
  {
    cerr<<"bad beginning position."
        <<endl;
    return 0;
  }

  if(start<1)
  {
    cerr<<"bad beginning position."
        <<endl;
    return 0;
  }

  if(count<2||count>number)
  {
    cerr<<"bad interval number"
        <<endl;
    return 0;
  }

  n=number;
  begin=start-1;
  m=count;

  return 1;
}

 


void initial(Jose *pJose)
{
  int lineCount=0;
  Jose *px=pJose;

  for(int i=1;i<=n;i++)
  {
    px->next=pJose+i%n;
    px->code=i;
    px=px->next;

    if((lineCount++%10)==0)
      cout<<endl;
    cout<<setw(4)<<i;
  }
  cout<<endl;
  pCur=pJose+n-1;
}

 

void count(int m)
{
  for(int i=0;i<m;i++)
  {
    pivot=pCur;
    pCur=pivot->next;
  }
}

 

void process()
{
  int l=0;
  for(int i=1;i<n;i++)
  {
    count(m);

    if((l++%10)==0)
      cout<<endl;
    cout<<setw(4)<<pCur->code;

    pivot->next=pCur->next;
    pCur=pivot;
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章