/*
编号是1,2,……,n的n个人按照顺时针方向围坐一圈,每个人持有一个密码(正整数)。一开始任选一个正整数作为报数上限值m,从第一个人开始顺时针方向自1开始顺序报数,报到m时停止报数。报m的人出列,将他的密码作为新的m值,从他在顺时针方向的下一个人开始重新从1报数,如此下去,直到所有人全部出列为止。设计一个程序来求出出列顺序。
*/
#include <iostream>
using namespace std;
//-------------------------------------------------------------------------
struct Jose
{
int code;
Jose* next;
};
int n, s, m;
Jose* pCur;
Jose* pivot;
//-------------------------------------------------------------------------
bool getValue();
Jose* CreateRing(); //创建链表
void countBoy(int m); //数m个小孩
void procss(); //排除n-1个小孩
//-------------------------------------------------------------------------
int main()
{
if (!getValue()) return 1;
Jose* PJose = CreateRing();
procss();
cout<<"/nThe winner is "<<pCur->code<<"/n";
delete[] PJose;
}
bool getValue()
{
cout<<"Please input boyNumber, startPosition, interValNumber:/n";
cin>>n>>s>>m;
if (n>=2 && s>=1 && s<=m && m>=1 && m<=n) return true;
cerr<<"failed in bad boyNumber or startPosition or interValNumber./n";
return false;
}
//-------------------------------------------------------------------------
Jose* CreateRing()
{
Jose* px = new Jose[n];
for(int i=1; i<=n; i++)
{
px[i-1].next = &px[i%n];
px[i-1].code = i;
}
cout<<"There are "<<n<<" boys./n";
pivot = &px[n-2];
pCur = &px[n-1];
countBoy(s-1);
return px;
}
//-------------------------------------------------------------------------
void countBoy(int im)
{
for (int i=0; i<im; i++)
{
pivot = pCur;
pCur = pCur->next;
}
}
void procss()
{
for (int i=1; i<n; i++)
{
countBoy(m);
static int line = 0;
cout<<" "<<pCur->code;
if (!(++line%10)) cout<<"/n";
pivot->next = pCur->next;
pCur = pivot;
}
}