// 先把程序给你,也许我写的复杂了些,不过你的程序更本不是C++ 程序,只不过用了 cin, cout 而已。
// 今天,已经有朋友关于这个问题提问了,虽然,我没兴趣来做这种趣味题,不过考虑到,这道题和数据结构有点关系,
// 我还是做了。显然,你看都没看啊。你的这道题,只是条件特殊化了而已,如果,你认真研究一下,可以自己改写我的程序的,就像我现在做的一样。
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
struct Person
{
int secretNumber;
int position;
int current_position;
Person * right;
Person * left;
};
class Josephu
{
private:
int total; // How many persons total
int n; // How many persons current
Person * person;
enum{ m = 3}; // at the begin we set the m value
Person * current;
public:
Josephu();
// void set_the_number_of_persons();
bool createJosephuCircle(int i);
// void set_m_value();
Person * bau_shu(const int m);
void run_Josephu();
~Josephu();
};
Josephu::Josephu()
{
total = 0;
n = 0;
person = NULL;
current = NULL;
}
bool Josephu::createJosephuCircle(int i)
{
total = n = i;
person = new Person[total];
if(person == NULL)
return false;
for(int j = 0; j<n; j++)
{
person[j].secretNumber = m;
person[j].position = person[j].current_position = j;
if(j == 0)
{
current = person;
person[j].left = &person[j+1];
person[j].right = &person[n-1];
}
else if(j == n-1)
{
person[j].left = &person[0];
person[j].right = &person[j-1];
}
else
{
person[j].left = &person[j+1];
person[j].right = &person[j-1];
}
}
return true;
}
/*
void Josephu::set_m_value()
{
cout<<"please enter the first m value.\n";
cout<<" m = ";
cin>>m;
}
*/
Person * Josephu::bau_shu(const int m)
{
Person * aus;
Person * temp;
Person * next;
int offset = (m)%n?(m)%n-1:n-1;
temp = current;
for(int i = 0; i<offset; i++)
{
temp = temp->left;
}
aus = temp;
current = aus->left;
aus->right->left = aus->left;
aus->left->right = aus->right;
// m = aus->left->secretNumber;
next = aus->left;
for(i = current->current_position; i<n; i++)
{
(next->current_position)--;
next = next->left;
}
cout<<aus->position<<" ";
n--;
return current;
}
void Josephu::run_Josephu()
{
while(n != 1)
{
bau_shu(m);
}
cout<<"\nThe Winner is in position(Begin with the position 0) : "<<current->position<<endl;
}
Josephu::~Josephu()
{
if(person && total>1)
delete [] person;
else
delete person;
}
int main()
{
Josephu aJosephu;
// aJosephu.set_the_number_of_persons();
aJosephu.createJosephuCircle(17); // create a Josephu Circle with 17 member
// aJosephu.set_m_value(); // set the m value at the begin
aJosephu.run_Josephu();
cout<<endl;
system("pause");
return 0;
}